I am afraid that all this stems from a misunderstanding of what mut means.
You need to distinguish between two terms:
vec![5, 6, 7] creates an instance of type Vecmy_vec is the binding, that is, the name given to the type instance, because it is easier to manipulate the instances by name (but not necessarily, cue Forth )
When you declare let mut my_vec , you:
- Variable Binding Declaration
- to which the
Vec instance is bound
The instance itself cannot be called mutable, it is pointless, as shown in the following valid fragment:
let mut my_vec = vec![5, 6, 7]; let other = my_vec; // ownership transfer let mut yac = other; // ownership transfer
In this fragment we see:
Vec instance bound to my_vec mutable binding- and then bound to the immutable binding of
other - and then
yac mutable binding
which, we hope, will demonstrate that volatility is not a property of an instance, but a binding.
Inherited variability comes into play here:
- If you have a mutable binding to an instance of
T ( let mut x: T = ...; ) or a binding to a mutable reference to an instance of T ( let x: &mut T = ...; ), then you can not only mutate its fields but also get mutable links to these fields to change their own fields ... recursively. - Conversely, if all you hold is an invariable reference to an instance of type
T ( let x: &T = ...; ), then all you can do is read its fields or get immutable references to these fields so that read their own fields ... recursively (*).
(*) Well, Ok, this is a simplification, cell types, for example, can be changed using immutable links; what the next day!
source share