TL ; DR:
A getter reads a private field. A setter changes it, but only to a value the class allows.
Rust has no special syntax for them. You write both as methods in the impl block, as in the Access Modifiers lesson. The getter get_age returns the private field. The setter set_age changes it.
struct Dog {
age: i32,
}
impl Dog {
fn new(age: i32) -> Dog {
Dog { age: age }
}
fn get_age(&self) -> i32 {
self.age
}
fn set_age(&mut self, value: i32) {
if value >= 0 {
self.age = value;
}
}
}
Full lesson:
In the Access Modifiers lesson, get_name let other code read a private field. Often other code must change a field too. A setter allows that, and it checks each new value first.
The getter
The getter only reads, so it takes &self. Its body is self.age, without a semicolon.
The setter
The setter changes the struct, so it takes &mut self. That's why rex is declared with let mut. Other code calls rex.set_age(4).
The rule
A dog's age can't be negative. So set_age changes self.age only when value is 0 or more. After rex.set_age(-5), the age stays as it was.
Why not a pub field?
With pub age, code in other modules could set it to -5. Nothing would check it. The setter keeps the rule inside the impl block.
Your task
The Dog struct keeps its age in the private field age. Add a getter get_age that returns it. Add a setter set_age that ignores negative values.
The code in main_function creates rex, then reads and sets its age.
Expected output:
Rex is 3
Rex is still 3
Rex is 4Free plan: 30 tutor messages. Premium is unlimited.
