A struct groups named fields. An impl block adds methods that read the fields through &self.

Program

Play the program to build a rectangle and compute its area.

structs.rs
Replay: real traced execution (multi-file project)
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 4, height: 3 };
    let area = rect.area();
    println!("{area}");
}
  1. rect ← (empty)

    12fn main() {13    let rec→ (empty)t = Rectangle { width: 4, height: 3 };14    let area = rect.area();15    println!("{area}");
  2. area ← 12

    13    let rect = Rectangle { width: 4, height: 3 };14    let are→ 12a = rect.area();15    println!("{area}");16}
    output12

Follow the Trace

  1. rect is Rectangle { width: 4, height: 3 }.
  2. The program calls rect.area().
  3. Inside the method, self.width is 4.
  4. self.height is 3.
  5. The return value is 12, and the program prints 12. | trace point | value | | --- | --- | | rect.width | 4 | | rect.height | 3 | | method call | rect.area() | | returned area | 12 | | stdout | 12 |
struct `struct Rectangle` groups related fields.
impl `impl Rectangle` attaches methods to the type.
&self `area(&self)` borrows the instance to read its fields.

Exercise: structs.rs

Reproduce the output 12, then trace which two fields the area method multiplies.