Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MODEL THE DOMAIN
BUILD NOTE 15 / 53

Put behavior beside the model.

Choose between borrowing, mutating, and consuming self.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/methods/src/main.rs
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());
}
↳ EXPECTED OUTPUT
1
  1. 1

    new returns Self without needing an instance.

  2. 2

    increment needs an exclusive borrow.

  3. 3

    value only borrows for reading.

From the extracted rust-workbench folder
cargo run -p lesson_methods

03 Mind the boundary

04 Your next build

A SMALL MISSION

Implement Rectangle::new and an area method using &self.

Reveal one possible solution +
solutions/methods/src/main.rs
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

QUICK SIGNAL CHECK

Which receiver allows mutation without consuming the instance?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.