Member-only story
Effective Rust uses a type system to express general behavior
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 & self
parameter indicates that the method can read content from the data structure, but does not modify the content.The & mut self
parameter indicates that the method may modify the contents of the data structure.The self
parameter representation method consumes data structures.