Member-only story

Effective Rust uses a type system to express general behavior

Beck Moulton
11 min readJun 7, 2024

--

Method

In the Rust type system, behavior first appears when methods are added to data structures: by self-identifying functions that act on instances of that type. This method encapsulates related data and code in a way similar to other Object Oriented languages; however, in Rust, given the widespread use of Rust enumeration types (see item 1), methods can be added to enumeration types in addition to struct types.

enum Shape {
Rectangle { width: f64, height: f64 },
Circle { radius: f64 },
}impl Shape {
pub fn area(&self) -> f64 {
match self {
Shape::Rectangle { width, height } => width * height,
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
}
}
}

The name of a method provides a label for the behavior it encodes, while the method signature provides type information for the input and output. The first input of a method is usually some form of self, indicating the operations the method may perform on the data structure:

  • The & selfparameter indicates that the method can read content from the data structure, but does not modify the content.
  • The & mut selfparameter indicates that the method may modify the contents of the data structure.
  • The selfparameter representation method consumes data structures.

Abstrat behavior

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet