Please consider this code:
let mut parent = Parent { value: 0, child: Child { value: 0, } };
let parent_mut = &mut parent;
parent_mut.value = 1;
let child_mut = &mut parent_mut.child;
child_mut.value = 2 + parent_mut.value;
The code seems to allow multiple mutable references to parent, albeit one is through the parent's child field. I'm a bit confused by this. For instance, I can think about these as being two independent references, one is to a &mut Parent, and the other to a &mut Child. But if I acquire the child reference like so:
let child_mut = &mut parent.child; // not parent_mut.child
...the compiler will give an error about two mutable borrows
So it seems the original code maintains a link between the two mutable references and allows them to co-exist. Is it appropriate to think of them as two allowable references to Parent, or one for Parent and one for Child? If they are indeed independent references then it feels like the compiler should allow functions to be written like so:
pub fn child_set_value(child: &mut Child, parent: &mut Parent) {
child.value = 3;
parent.value = 3;
}
...but invoking such a function is impossible as it means duplicating borrows:
child_set_value(child_mut, parent_mut);
child_mut and parent_mut are allowed to co-exist, but at the moment of passing them to a function, new independent borrows take place and there is no longer this link between the two references. Is this the right way to think about it?
I assume the common workaround to allow the references to exist inside a function would be to use RefCell, but I haven't yet researched RefCell enough to be able to convert this example. For now I just wanted clarification that the two references can co-exist, just not within a function.
Thank you very much for your comments!
This is my full example:
Rust Playground Link