Sub topic 6
Adding behavior with impl blocks
This chapter assumes you can define a struct, create instances, and read and change fields. It also assumes you know the basics of ownership and borrowing (move, &, &mut). Here you will attach functions to a struct with an impl block. The next chapters cover constructors and the self receivers in more detail.
What an impl block is
A struct holds data. An impl block (short for "implementation") holds the functions that belong to that type. Everything inside it is called an associated item, because it is tied to the type named after impl.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let r = Rectangle { width: 3, height: 4 };
println!("area = {}", r.area());
}The impl Rectangle line says that the functions inside are for Rectangle. Inside the block, Self is an alias for the type being implemented, so Self here means Rectangle.
Two kinds of functions
An impl block can hold two kinds of functions. The first parameter decides which kind you have.
| First parameter | Kind | How you call it |
|---|---|---|
| `self`, `&self`, or `&mut self` | Method | `value.name()` |
| Anything else, or none | Associated function | `Type::name()` |
area above is a method. It takes &self, so it borrows the instance and can read its fields. A function with no self, such as a constructor, is called with the type name and ::.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Self {
Self { width, height }
}
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let r = Rectangle::new(3, 4);
println!("area = {}", r.area());
}Multiple impl blocks
You can write more than one impl block for the same type. The compiler merges them. This is legal and sometimes useful, for example to group related methods or to separate methods that need different trait bounds.
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Self {
Self { count: 0 }
}
}
impl Counter {
fn increment(&mut self) {
self.count += 1;
}
fn get(&self) -> u32 {
self.count
}
}
fn main() {
let mut c = Counter::new();
c.increment();
c.increment();
println!("{}", c.get());
}For a simple struct, one block is usually clearer.
Where impl blocks can live
An impl block for your own type can be in any module of the same crate, not only next to the struct. It must be in a scope where the type is visible. You cannot add inherent methods to a type from another crate, such as Vec or String. For those, you define a trait instead.
Common errors
- Forgetting
self. If you writefn area() -> u32and callr.area(), the compiler reports thatareais an associated function, not a method. Add&selfor call it asRectangle::area(). - Calling a method with
::and no instance.Rectangle::area()fails becauseareaneeds a receiver. Writer.area()orRectangle::area(&r). - Mutating through
&self. Assigning toself.widthinside a&selfmethod is an error. The method needs&mut self. - Missing
muton the variable. Calling a&mut selfmethod on a non-mutbinding is an error even if the method is correct.
Exercise
A struct Light has the method fn toggle(&mut self). Why does let l = Light { on: false }; l.toggle(); fail to compile, and what is the fix?
Show answer
The method needs a mutable borrow, but l was declared without mut. Declare it as let mut l = Light { on: false };.