9.7 Getters and Setters

For additional control or invariants, you can define getters and setters.

9.7.1 Getters

impl Person {
    fn name(&self) -> &str {
        &self.name
    }
}

9.7.2 Setters

impl Person {
    fn set_age(&mut self, age: u8) {
        if age >= self.age {
            self.age = age;
        } else {
            println!("Cannot decrease age.");
        }
    }
}

These methods allow you to validate or limit how fields are accessed and modified.