9.8 Getters and Setters

Getters and setters are methods used to access and modify struct fields, often employed to enforce encapsulation and maintain invariants.

9.8.1 Getters

A getter method returns a reference to a field.

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

9.8.2 Setters

A setter method modifies a field.

impl Person {
    fn set_age(&mut self, age: u8) {
        self.age = age;
    }
}
  • Setters can include validation logic to ensure the field is set to a valid value.

Example:

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