The tile says it all. I was going through the rust doc on std::cell
module and could not completely comprehend the various interpretations of the phrase "inherited mutability": what does "inherited" mean here in this context ? What is getting inherited here ?
I guess I'd say...
Vec<T>
has inherited mutability for T
, so you can't mutate the T
through a &Vec<T>
.
struct
s have inherited mutability for their fields, so you can't mutate a S.field
through a &S
.
And so on.
(If T
or a field contains an UnsafeCell<U>
, the contents of the UnsafeCell
(U
) may be mutated via shared reference (&
).)
I personally prefer the term "shared mutability" over "interior mutability", but don't really have an alternative term for "inherited mutability". Instead you introduce shared borrowing as by-default immutable, and then introduce shared mutability as a way to regain mutability.
(A nested shared reference inside that could then reintroduce immutability.)
Here's an article more in line with that mental model.
https://limpet.net/mbrubeck/2019/02/07/rust-a-unique-perspective.html
As I find the definition in the documentation of std::cell
also a bit imprecise I searched for the term and found this article which discusses inherited mutability. As far as I can tell @quinedot's interpretation is essentially consistent with this.
It seems as if in the early days of the language it was not that obvious that the way you can access an inner element or field of a data structure should be inherited from the access you have to the entire data structure.
Ack. Is there a way to propose updating the doc of std::cell to clarify the context and interpretation of it ? (or) is this captured in the rust-reference/rustonomicon ?
You could send a PR.
I hadn't noticed the term "inherited mutability" before, but I like it. One of the things that needs explaining to newcomers to Rust is that there's no such thing as an "immutable type" — that (non-interior) mutability is determined by the place or reference, not the choice of type. I'll want to say "mutability is inherited except for specific cases" the next time this comes up.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.