fn main(){
let mut a1 = String::from("test");
let b = &mut a1;
let c: &mut String = b;
// let c = b;
println!("c {:p}",c);
c.push_str(" addition");
println!("b {:p}",b); // it gives a compile time error when "let c = b;" since the ownership is transferred from b to c
// println!("c {:p}",c); // the above statement println!("{}",b) throws a compile time error if this line is uncommented
}
I was trying to learn rust and encountered something I could not comprehend. There are three variables a, b and c.
a is a string
b is a mutable reference of a
and c is .... for now ignore it.
As far as I understand you cannot create two mutable references to a data variable and when u assign it to a variable its ownership gets transferred.
When I assign the variable b to c i.e., let c = b, the ownership of variable b gets transferred to c.
let mut a1 = String::from("test");
let b = &mut a1;
let c = b;
c.push_str(" addition");
println!("c {}",c);
println!("b {}",b); // error
But when I assign it like this let c: &mut String = b;(with type declaration), The ownership is not transferred.
let mut a1 = String::from("test");
let b = &mut a1;
let c: &mut String = b;
c.push_str(" addition");
println!("c {}",c);
println!("b {}",b); // no error
I am confused why this works without any issue.
From my understanding I assume that c has become a mutable reference of b. But here I have to make b mutable and pass it as reference to c while in the code above b was not mutable and I have passed it like a normal variable.
let mut a1 = String::from("test");
let mut b = &mut a1;
let c = &mut b;
c.push_str(" addition");
println!("c {}",c);
println!("b {}",b); // no error