I have the following code that compiles and runs without any issues -
#[derive(Debug)]
pub struct A<'a> {
field: &'a mut String
}
fn main() {
let mut b = "Hello".to_owned();
let a = A { field: &mut b };
let c = A { field: a.field };
c.field.push('+');
a.field.push('+');
//println!("{:?}", c);
// println!("{:?}", a);
}
But I am confused as to why this code is working, or even compiling, for the following reasons -
It seems like we are holding two mutable references to the same object
b
. This is evident since bothc.field.push('+');
anda.field.push('+');
succeed.Why does this statement -
let c = A { field: a.field };
, not move field out of A (since mutable references are not copyable) and invalidate A?