Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a mutable String reference implement Copy [duplicate]

Tags:

rust

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);
}
like image 404
Shiva Avatar asked Jun 27 '26 20:06

Shiva


1 Answers

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);
}
like image 102
jonasbb Avatar answered Jul 02 '26 12:07

jonasbb