3

In the below code I was expecting the compiler to complain about use of moved value: xref on hello function's second call since mutable references do not implement Copy. The compiler doesn't raise any such error. What am I missing here?

fn main() {
    let mut x: String = "Developer".to_string();
    let x_ref: &mut String = &mut x;
    hello(x_ref);
    hello(x_ref);
}

fn hello(a: &mut String) {
    println!("Hello {}", a);
}
Shiva
  • 2,627
  • 21
  • 33
  • 1
    Regarding your [deleted comment](https://stackoverflow.com/questions/67406730/is-it-possible-to-define-a-slice-with-a-fixed-size?noredirect=1#comment119153603_67406730) — *since the existing questions have very different titles, they will not be able to find thos e questions themselves before asking* — yes, that's **exactly why** SO has duplicates. By marking your question as a duplicate, people would find the correct answer if they used your wording. By deleting your question, you take away that possibility. **Duplicates are not a bad thing**. – Shepmaster May 06 '21 at 17:47

1 Answers1

4

Your example uses the mutable references after each other, which allows the compiler to perform an implicit reborrow. It basically turns this code into this:

    hello(&mut *x_ref);
    hello(&mut *x_ref);

Now you have two separate mutable borrows each only for the lifetime of the function call, thus they do not conflict with each other.

You see an error if you try to use it two times simultaneously.

fn main() {
    let mut x: String = "Developer".to_string();
    let x_ref: &mut String = &mut x;
    hello(x_ref, x_ref);
}

fn hello(a: &mut String, b: &mut String) {
    println!("Hello {} and {}", a, b);
}
jonasbb
  • 2,131
  • 1
  • 6
  • 25