Limited mutation with visibility

I have, simplified:

pub struct AState P
....
  bf: B,
...
}

and in another module

pub struct B {
   pub f1: String,
   pub f2: String,
...
}

Due to the nature of the program (iced) there are thigns with mut reference to an instance of AState. I have made the fields of B public so that the various view and update logics can get at the fields, as I feel the structure is stable enough to expose. The only way B instances themselves get "changed" is by creating a new instance, and replacing the one stored in teh instance of AState. So I would prefer to mark, so I don't confuse myself when maintaining this code, that the fields of B are accessible but should never be directly mutated. Is there a way I missed to mark that, or is the only way by constructing accessor methods and makign the fields private? (Part of the reason I am exploring this is that folks in an earlier thread, if I understood them properly, indicated that if the structure is stable and clear, making the fields pub is better than defining accessors.)
Thanks,
Joel

There is a proposal to add this ability to limit field mutability, but it is not currently implemented. Using accessors is the only way to enforce such a constraint right now.

Using public fields instead of accessors is a good principle, but it is only really important when the fields are being mutated (in which case it reduces the number of exclusive borrow conflicts that may be encountered).

Thanks for the helpful reply both on the question itself, and the context around it.
Joel

Another way[1] is to have a "view type":

pub struct BView<'a> {
    // Let's say it was okay to mutate this one
    pub f1: &'a mut String,
    // But not this one
    pub f2: &'a str,
}

impl B {
    fn view(&mut self) -> BView<'_> { ... }
}

...but since you only need shared access, the benefits versus typical per-field accessors may be not be worth it, as multiple shared accesses don't conflict with each other.


  1. well, could be seen as a specialized type of accessor method I suppose â†Šī¸Ž

Interesting idea. I can imagine cases where htat would be helpful.
Thanks.