Put behavior beside the model.
Choose between borrowing, mutating, and consuming self.
01 Understand the contract
An impl block attaches behavior to a type. A method has a self receiver: &self borrows for reading, &mut self borrows exclusively for mutation, and self consumes the value. An associated function without a self receiver is called using Type::function and often constructs a value. Keeping fields private and exposing purposeful methods can preserve invariants. A constructor is an ordinary function by convention, not a language keyword.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
struct Counter {
value: u32,
}
impl Counter {
fn new() -> Self {
Self { value: 0 }
}
fn increment(&mut self) {
self.value += 1;
}
fn value(&self) -> u32 {
self.value
}
}
fn main() {
let mut c = Counter::new();
c.increment();
println!("{}", c.value());
}1
- 1
new returns Self without needing an instance.
- 2
increment needs an exclusive borrow.
- 3
value only borrows for reading.
cargo run -p lesson_methods03 Mind the boundary
04 Your next build
Implement Rectangle::new and an area method using &self.
Reveal one possible solution +
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);
assert_eq!(r.area(), 12);
}05 Check your reasoning
Which receiver allows mutation without consuming the instance?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.