Sub topic 6
Adding behavior with impl blocks
This chapter assumes you can define a struct, create instances, and read its fields. It also assumes you know the basics of moves and borrows (& and &mut). Here you learn where a struct's behavior lives and how Rust finds it.
Data and behavior are declared separately
A struct declaration lists fields and nothing else. Functions that belong to the type go in an impl block (short for implementation). The block names the type and holds the functions.
struct Counter {
count: u32,
step: u32,
}
impl Counter {
const DEFAULT_STEP: u32 = 1;
fn new() -> Self {
Self {
count: 0,
step: Self::DEFAULT_STEP,
}
}
fn increment(&mut self) {
self.count += self.step;
}
}
impl Counter {
fn count(&self) -> u32 {
self.count
}
fn is_even(&self) -> bool {
self.count % 2 == 0
}
}
fn main() {
let mut c = Counter::new();
c.increment();
c.increment();
println!("{}", c.count());
println!("{}", Counter::count(&c));
println!("{}", c.is_even());
}This prints 2, 2, and true. Several things in it are worth noting.
Selfis an alias for the type named afterimpl. WritingSelf { ... }andSelf::DEFAULT_STEPmeans you don't repeatCounter, and renaming the struct touches fewer lines.- A block can hold functions and associated constants. An associated constant such as
DEFAULT_STEPis reached withType::NAMEorSelf::NAME. - A struct can have more than one
implblock. The compiler merges them. Each one here is a plain inherent block, meaning it adds functions directly to the type and implements no trait. countis both a field and a method. The parentheses tell the compiler which one you mean:c.countreads the field andc.count()calls the method. This is the usual way to write a getter.
Two ways to call the same function
A function whose first parameter is self, &self, or &mut self is a method. You can call it with dot syntax or with path syntax.
struct Counter {
count: u32,
}
impl Counter {
fn count(&self) -> u32 {
self.count
}
}
fn main() {
let c = Counter { count: 7 };
println!("{}", c.count());
println!("{}", Counter::count(&c));
}The two calls are the same. Dot syntax adds the borrow for you, and path syntax makes you write &c yourself. A function with no self parameter is an associated function. You can only call it with the path form, such as Counter::new(). The next chapters cover constructors and the three receivers in detail. For now, remember that the first parameter decides whether dot syntax is available.
Why you might split a type across several blocks
One block is enough for most types. Splitting is useful in a few cases.
- You want to group related methods, such as construction in one block and queries in another.
- You want a block that only applies to some instantiations of a generic type.
- You want
#[cfg(...)]attributes on a whole block, for example for test-only helpers.
The generic case looks like this:
struct Wrapper<T> {
value: T,
}
impl<T> Wrapper<T> {
fn new(value: T) -> Self {
Self { value }
}
}
impl Wrapper<f64> {
fn double(&self) -> f64 {
self.value * 2.0
}
}
fn main() {
let w = Wrapper::new(2.5);
println!("{}", w.double());
}impl<T> Wrapper<T> applies to every Wrapper. impl Wrapper<f64> adds double only when T is f64. Calling double on a Wrapper<String> is a compile error. Generics get their own chapter later.
Other types can have impl blocks too
impl is not specific to structs. Enums use the same syntax.
enum Light {
Red,
Green,
}
impl Light {
fn can_go(&self) -> bool {
matches!(self, Light::Green)
}
}
fn main() {
println!("{}", Light::Red.can_go());
println!("{}", Light::Green.can_go());
}Where an impl block may live
Rust enforces two placement rules.
- An inherent
implmust be in the same crate as the type. You cannot add inherent methods toVec<T>orString. The compiler reports error E0116 for this. To add behavior to a foreign type, define a trait and implement it, or wrap the type in your own struct (the newtype pattern, covered later). - Inside a crate, the block can be in a different module from the struct, but privacy still applies. Private fields are visible in the module that defines the struct and in its child modules. An
implin a sibling module or in the parent cannot touch them.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `no method named x found` | The function has no `self` parameter, or it is in a block with different generic bounds. | Call it as `Type::x(...)`, or add the receiver. |
| `expected value, found struct Self` or an unresolved name for a field | Writing `count` instead of `self.count` inside a method. | Fields are never in scope implicitly. Always write `self.field`. |
| `duplicate definitions with name x` (E0592) | Two `impl` blocks for the same type define the same name. | Rename one. Multiple blocks share one namespace. |
| `cannot borrow ... as mutable` | Calling a `&mut self` method on a binding declared without `mut`. | Declare `let mut c = ...`. |
| `cannot define inherent impl for a type outside of the crate` (E0116) | `impl Vec<u8> { ... }` | Use a trait or a newtype. |
| `field x of struct is private` | An `impl` in a module that cannot see the fields. | Move the block into the defining module or a child, or add a `pub` accessor. |
The first row catches many learners. Inside an impl, you reach a sibling function through Self::name(...) or self.name(...). A bare name(...) looks for a free function and will not find it.
Sketch of how the compiler resolves a method call
When you write c.is_even(), the compiler takes the type of c and looks for an inherent method called is_even on it. It tries the receiver as Counter, then &Counter, then &mut Counter, and then repeats with any dereferenced types. The first match wins, and the compiler inserts the & or &mut for you. Inherent methods take priority over trait methods with the same name. A later chapter covers this order in full. The practical consequence is that a method's receiver kind controls whether the call site needs mut, and whether the value is still usable afterward.
Exercises
Exercise
A struct Temp { celsius: f64 } has a method fn celsius(&self) -> f64. Is it legal for the struct to have a field and a method with the same name, and how do you read each?
Show answer
Yes, it is legal. Fields and methods live in different namespaces. t.celsius reads the field (and only works where the field is visible). t.celsius() calls the method.
Exercise
You write impl Vec<i32> { fn total(&self) -> i32 { self.iter().sum() } } in your crate. The compiler rejects it. Why, and what are two ways to get a total method?
Show answer
An inherent impl must be in the same crate as the type, and Vec comes from the standard library (error E0116). You can define a trait with a total method and implement that trait for Vec<i32>. You can also wrap the vector in your own struct, such as struct Numbers(Vec<i32>);, and write an inherent impl Numbers with total.