What is the right patter for a lazy field?


#1

I have a field that I only want to calculate when is really necessary I access it via a function.

struct MyStruct {
    expensive: Option<i32>,
}

impl MyStruct {

   fn get_expensive(&self)  -> i32 {
        if self.expensive.is_none() {
             self.calculate()
        }
        self.expensive.unwrap()
   }
}

This does not work because calculate() needs to mutate self. But If use mut then it means that I need to add mut to all functions calling get_expensive. Is there a way out of this?


#2

Yes! You need “interior mutability” here.

https://doc.rust-lang.org/std/cell/#implementation-details-of-logically-immutable-methods