I want Foo.a to be immutable. However, if I were to make it private and write an immutable accessor, then I couldn't call: bar(&foo.a, &mut foo.b)
anymore, since the accessor fn get_a(&self) -> &A { &self.a }
would borrow the entire Foo on a call.
How do I work around this without creating a function which borrows every field (some mutable and some immutable, depending on which fields should remain unmutated)?
it always surprised me that Rust fields aren't immutable by default, given that's how identifiers work everywhere else in the language ¯_(ツ)_/¯
and yeah, while you can make it non-pub and write a getter, that only enforces immutability on the external consumers of your class, not the internal developers (future you!) – so I'm very much looking forward to readonly struct fields
Well… “everywhere else” lack of mut is not a serious restriction: you may always move from immutable variable to mutable one and do as many modifications as you want… that wouldn't work with fields, there lack mutability would actually mean something more strict.
oh true, icwym. The same should apply to struct fields tho, right? mut if you can change it in-place, nothing if you can't; but either way, if you want, you can still move out of the field to have ownership and mutability, leaving a partially moved struct. So mut is only applying when you're not moving the field out
One could argue that if a field a must uphold invariants that depend on other (private) fields in its enclosing struct, while another field b in the same struct is freely mutable, then b arguably does not belong in that struct.