I understand there can only be one mut& for an object. But what if the object contains another object, are we not allowed to take refernce for the child object as well?
I tried with some exmpales and the result is confusing:
#[derive(Debug)]
struct Value {
value: i32,
}
#[derive(Debug)]
struct Container {
value: Value,
value2: i32,
}
fn main() {
let mut obj1 = Container { value: Value { value: 12 }, value2: 1 };
let mut_ref1 = &mut obj1;
let mut_ref2 = &mut obj1.value;
mut_ref2.value = 1;
}
This one compiles, but the following one does not:
#[derive(Debug)]
struct Value {
value: i32,
}
#[derive(Debug)]
struct Container {
value: Value,
value2: i32,
}
fn main() {
let mut obj1 = Container { value: Value { value: 12 }, value2: 1 };
let mut_ref1 = &mut obj1;
let mut_ref2 = &mut obj1.value;
mut_ref1.value2 = 111;
}
The first example shows I can take mutable reference to child object at the same time, but the second example shows I cannot do that.
If in the first example, compiler is smart enough to tell mut_ref1
is not used, why it cannot do the same for mut_ref2
in the second example?