What is the right patter for a lazy field?


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() {

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?


Yes! You need “interior mutability” here.