Sub topic 5
Adding behavior with impl
This chapter assumes you know structs, impl blocks on structs, and the difference between self, &self, and &mut self. It also assumes you can write a basic match. Here you attach methods to enums so the behavior lives next to the data.
Methods on an enum
An enum gets methods the same way a struct does, with an impl block. Inside a method, self is the enum value, so the usual body is a match on self.
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Rectangle { width, height } => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
fn main() {
let shapes = [
Shape::Circle { radius: 1.0 },
Shape::Rectangle { width: 2.0, height: 3.0 },
Shape::Triangle(3.0, 4.0, 5.0),
];
for shape in &shapes {
println!("{:.2}", shape.area());
}
}The program prints 3.14, 6.00, and 6.00. The match must cover every variant. If you add a Square variant later, area stops compiling until you handle it. The compiler points you to every method that needs an update.
Choosing the receiver
The first parameter decides how the method uses the value.
| Receiver | Meaning | Typical use |
|---|---|---|
| `&self` | Read the value | Queries such as `area` |
| `&mut self` | Change the value in place | Moving to another variant |
| `self` | Consume the value | Converting into something else |
An associated function has no self. You call it with ::, as in Light::start(). It is the usual place for constructors.
Transitions that return a new variant
A method can compute the next variant. When the enum is Copy, taking self by value is cheap and convenient. A &mut self method can then replace the current value with *self = ....
#[derive(Debug, Clone, Copy)]
enum Light {
Red,
Green,
Yellow,
}
impl Light {
fn start() -> Light {
Light::Red
}
fn next(self) -> Light {
match self {
Light::Red => Light::Green,
Light::Green => Light::Yellow,
Light::Yellow => Light::Red,
}
}
fn advance(&mut self) {
*self = self.next();
}
}
fn main() {
let mut light = Light::start();
light.advance();
println!("{:?}", light);
light.advance();
println!("{:?}", light);
}This prints Green, then Yellow.
Common errors
- Moving out of a borrow. If a method takes
&selfand matchesselfwhile binding a non-Copyfield by value, the compiler reports "cannot move out ofself". Match onselfas a reference, asareadoes, and the bindings become references. - Using a value after
selfconsumed it. A method that takesselfmoves the value unless the type isCopy. Calling another method on the same variable then fails. DeriveCopyfor small enums likeLight, or switch to&self. - Forgetting
*self =. Writingself = self.next();in a&mut selfmethod does not compile. You must assign through the reference.
Exercise
Add a perimeter(&self) -> f64 method to Shape. Which receiver should it use, and what happens if you forget to handle Triangle?
Show answer
Use &self, because the method only reads the value. A circle's perimeter is 2.0 * PI * radius, a rectangle's is 2.0 * (width + height), and a triangle's is a + b + c. If you leave out the Triangle arm, the code does not compile, because the match is not exhaustive.