Once an object has been built, we may modify its data through setter
methods. Those methods take a mutable reference to the self
instance, and thus can modify the values of the fields. We usually name
the setter methods using the set_ prefix.
As an example, let us write a struct representing the weight of a
car, with its empty weight and the current volume of petrol:
struct Car {
weight: f32, /* Empty weight in kg */
petrol_vol: f32, /* Volume of petrol inside the tank in L */
}The constructor accepts only the empty weight, the volume of petrol being set to a default value of 0L:
impl Car {
fn new(weight: f32) -> Self {
Self {
weight,
petrol_vol: 0.0,
}
}
}We implement a builder setter for the volume of petrol:
impl Car {
fn with_petrol(mut self, vol: f32) -> Self {
self.petrol_vol = vol;
self
}
}And also a setter method:
impl Car {
fn set_petrol(&mut self, vol: f32) {
self.petrol_vol = vol;
}
}We create an instance of Car:
let mut car = Car::new(800.0).with_petrol(60.0);
(car.weight, car.petrol_vol)(800.0, 60.0)And we modify the petrol volume in this instance using the setter method:
car.set_petrol(40.0);
(car.weight, car.petrol_vol)(800.0, 40.0)