In Rust, you don't specify mutability inside a struct
, but it is inherited from the variable binding. That's great, but is it possible to force a field to be always immutable, even when the root is mutable?
Something like this hypothetical syntax:
struct A {
immut s: Shape, // immutable by design
bla: Bla, // this field inheriting (im)mutability
}
let mut a = make_a();
a.s = x/*...*/; // illegal
This would help to maintain nice semantic restrictions in a program, just like Java's final
does (in a very limited way).
Also, we could imagine this kind of struct
having some non-owning references to internal immutable data, taking advantage of this immutability...
priv
and don't modify it in any code inside the same module, it is effectively immutable. And of course one can always replacea
wholesale (a = make_another_a();
), which may or may not be a problem. – Howlett