Sub topic 5
Adding behavior with impl
This chapter assumes you can read basic Rust, define enums whose variants carry data, and write a simple match. It also assumes you know what a move and a borrow are. Here you attach functions to an enum with an impl block, choose the right self receiver for each one, and avoid the errors that come with that choice.
Why put behavior on the enum
A free function such as fn area(shape: &Shape) -> f64 works. A method keeps the logic next to the type, so a reader who finds Shape also finds everything it can do. Methods also let you call shape.area() and chain calls.
Enums use the same impl syntax as structs. The body of a method on an enum is almost always a match on self, so the exhaustiveness check from the previous chapter covers every method you write.
Your first impl block
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}
impl Shape {
fn square(side: f64) -> Self {
Self::Rectangle { width: side, height: side }
}
fn name(&self) -> &'static str {
match self {
Self::Circle { .. } => "circle",
Self::Rectangle { .. } => "rectangle",
Self::Triangle(..) => "triangle",
}
}
fn area(&self) -> f64 {
match self {
Self::Circle { radius } => std::f64::consts::PI * radius * radius,
Self::Rectangle { width, height } => width * height,
Self::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
fn perimeter(&self) -> f64 {
match self {
Self::Circle { radius } => 2.0 * std::f64::consts::PI * radius,
Self::Rectangle { width, height } => 2.0 * (width + height),
Self::Triangle(a, b, c) => a + b + c,
}
}
}
fn main() {
let shapes = [
Shape::Circle { radius: 1.0 },
Shape::square(2.0),
Shape::Triangle(3.0, 4.0, 5.0),
];
for shape in &shapes {
println!(
"{}: area {:.2}, perimeter {:.2}",
shape.name(),
shape.area(),
shape.perimeter()
);
}
}The output is:
circle: area 3.14, perimeter 6.28
rectangle: area 4.00, perimeter 8.00
triangle: area 6.00, perimeter 12.00Three details are worth noting:
Selfinside animpl Shapeblock is an alias forShape.Self::Circle { radius }andShape::Circle { radius }mean the same thing. UsingSelfmeans you do not edit every method if you rename the enum.squarehas noselfparameter. It is an associated function, called withShape::square(2.0). Constructors are the usual use. They give a short name to a common variant.- In
name, the pattern{ .. }and(..)ignore the fields you do not need.
Choosing the receiver
The first parameter decides how a method uses the value. This is the most important choice in an impl block.
| Receiver | Meaning | Call site | Typical use |
|---|---|---|---|
| `&self` | Borrow read-only | `v.area()` | Queries: `area`, `name`, `is_ready` |
| `&mut self` | Borrow mutably | `v.advance()` | Changing the value in place |
| `self` | Take ownership | `v.into_text()` | Converting or consuming the value |
| none | Associated function | `Shape::square(2.0)` | Constructors, constants |
Start with &self and move to a stronger receiver only when the body needs it.
Mutating in place with &mut self
A method that changes which variant a value is must replace the whole value. Assign through *self:
#[derive(Debug, Clone, Copy, PartialEq)]
enum Light {
Red,
Green,
Yellow,
}
impl Light {
const ALL: [Light; 3] = [Light::Red, Light::Green, Light::Yellow];
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 seconds(&self) -> u32 {
match self {
Light::Red => 30,
Light::Green => 25,
Light::Yellow => 5,
}
}
}
fn main() {
let mut light = Light::Red;
for _ in 0..4 {
println!("{:?} for {}s", light, light.seconds());
light.advance();
}
let cycle: u32 = Light::ALL.iter().map(|l| l.seconds()).sum();
println!("full cycle: {cycle}s");
}This prints Red for 30s, Green for 25s, Yellow for 5s, Red for 30s, then full cycle: 60s.
next takes self by value. That is cheap and convenient here because Light derives Copy, so the caller keeps its original. advance takes &mut self and calls next, which copies *self implicitly. The const ALL is an associated constant. It lives on the type and is reached as Light::ALL.
Receivers and data-carrying variants
Non-Copy data changes the picture. Here the variant owns a String:
#[derive(Debug)]
enum Message {
Text(String),
Quit,
}
impl Message {
fn text_len(&self) -> usize {
match self {
Message::Text(s) => s.len(),
Message::Quit => 0,
}
}
fn shout(&mut self) {
match self {
Message::Text(s) => s.make_ascii_uppercase(),
Message::Quit => {}
}
}
fn into_text(self) -> String {
match self {
Message::Text(s) => s,
Message::Quit => String::new(),
}
}
}
fn main() {
let mut msg = Message::Text(String::from("hello"));
println!("{}", msg.text_len());
msg.shout();
println!("{:?}", msg);
let text = msg.into_text();
println!("{text}");
}The output is 5, Text("HELLO"), then HELLO.
When you match on self and self is &Message, the binding s becomes a &String. When self is &mut Message, s becomes a &mut String. Rust does this automatically. The next chapters on destructuring and binding modes explain the rule in full.
into_text takes self by value, so s is the String itself, moved out of the enum. The name follows the standard library convention: into_* consumes the value, as_* borrows it cheaply, and to_* makes a new value. After msg.into_text(), using msg is a compile error because it was moved.
Common errors
- Using
selfwhen&selfis enough. Aselfreceiver on a non-Copyenum makes every caller give up the value. Callers then have to clone it or lose it. - Forgetting the wildcard cost. If you add a
_ =>arm to a method, a new variant added later compiles silently into that arm. Prefer listing every variant in methods where each variant should be a deliberate decision. - Assigning to a field of the wrong variant. An enum value holds one variant at a time. To change
Message::QuitintoMessage::Text, assign a whole new value with*self = .... You cannot assign to a field that does not exist in the current variant. - Mixing up
Selfandself.Selfis a type andselfis a value.Self::Quitnames a variant, andselfis the receiver.
Multiple impl blocks and traits
You may write several impl Shape blocks, even in different modules of the same crate. Splitting them is useful when one block holds constructors and another holds conversions.
Behavior that comes from a trait goes in a separate block, impl Trait for Enum. Two common examples are impl std::fmt::Display for Light and impl From<ParseIntError> for ConfigError. A later chapter on error enums uses the second form. Inherent methods, written in a plain impl, take priority over trait methods with the same name.
Exercise
Add a method fn scale(&mut self, factor: f64) to the Shape enum. It should multiply every length in the shape by factor. Which receiver does it need, and why can the body not use self by value?
Show answer
It needs &mut self, because it changes the existing value without replacing the variant. A self receiver would move the shape into the method and the caller would lose it, unless the method returned a new shape. The body is a match on self where each binding is a &mut f64. For example: match self { Self::Circle { radius } => *radius *= factor, Self::Rectangle { width, height } => { *width *= factor; *height *= factor; } Self::Triangle(a, b, c) => { *a *= factor; *b *= factor; *c *= factor; } }.
Exercise
A Light method is written as fn reset(self) { ... } and called as light.reset(); println!("{:?}", light);. This compiles for Light but would fail for Message. Why?
Show answer
Light derives Copy, so light.reset() copies the value and light stays usable. Message holds a String and is not Copy, so a self receiver moves it, and the later use of msg is a use-after-move error. The fix is to take &mut self or to return a new value.