II
🏗️ Structs & Enums
Defining Structs
Concept
Structs let you create custom data types by grouping named fields together. Unlike tuples, struct fields have names so you don't need to remember order. Structs can have methods defined in impl blocks. Methods that take &self read data, &mut self modify it, and self (rare) consume it.
example.rs
struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    // Associated function (no self) — called like Rectangle::new(...)
    fn new(width: f64, height: f64) -> Rectangle {
        Rectangle { width, height }
    }
    
    // Method — called on an instance: rect.area()
    fn area(&self) -> f64 {
        self.width * self.height
    }
    
    fn is_square(&self) -> bool {
        self.width == self.height
    }
}

fn main() {
    let rect = Rectangle::new(4.0, 6.0);
    println!("Area: {}", rect.area());       // 24.0
    println!("Square? {}", rect.is_square()); // false
}
Quick Check

What does #[derive(Debug)] do for a struct?

1 / 2