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
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}");
}
struct `struct Rectangle` groups related fields.
impl `impl Rectangle` attaches methods to the type.
&self `area(&self)` borrows the instance to read its fields.