Something like this compiles and runs fine:
#[derive(Clone)]
struct Member {
x: i32,
}
fn main() {
let mut arr = vec![Member { x: 5 }; 5];
arr[0].x = 25;
println!("{}", arr[0].x); // Gives 25
}
Is it because if a reference to a container such as Vec
is made mutable, then its elements "inherit" its mutability?
In general, mutability is "inherited" by the fields of a type depending on the binding of the variable. From The Rust Programming Language's chapter on defining structs:
If the instance is mutable, we can change a value by using the dot
notation and assigning into a particular field
[...]
Note that the entire instance must be mutable
However, that's not what's happening here. As Veedrac points out in the comments, you aren't accessing the fields of the container, but you are calling a method.
The []
operator is powered by the IndexMut
trait:
pub trait IndexMut<Idx>: Index<Idx>
where
Idx: ?Sized,
{
fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
}
Your code translates to something akin to:
{
let tmp: &mut Member = IndexMut::index_mut(&mut arr, 0);
tmp.x = 25;
}
In this case, nothing is "inherited", it's explicitly granted via the method implementations.
See also:
- Returning a struct containing mutable values