-1
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
Herohtar
  • 4,958
  • 4
  • 31
  • 39
Shatrugna
  • 1
  • 1
  • 1
    Does this answer your question? [Do mutable references have move semantics?](https://stackoverflow.com/questions/62960584/do-mutable-references-have-move-semantics) The answer to this question addresses how adding a type annotation causes reborrowing instead of moving. _("Implicit reborrows happen whenever the target type is already known to be a mutable reference by the compiler")_ – cdhowie May 25 '22 at 18:33
  • Mutable references are exclusive so they can't be `Copy`d and therefore should be *moved* on each use. However, for convenience, the compiler will implicitly *reborrow* the mutable reference so that it can continue to be used. Unfortunately though, the situations where the compiler will and won't add an implicit reborrow aren't particularly clear or obvious. – kmdreko May 25 '22 at 18:35

0 Answers0