Mutable reference is not Copy type

I was told mutable reference is not Copy type but this compiles. What did i get wrong?

fn main() {
    let mut table = Table::new();
    table.insert("Gesualdo".to_string(), vec!["many madrigals".to_string(), "Tenebrae Responsoria".to_string()]);
    table.insert("Caravaggio".to_string(), vec!["The Musicians".to_string(), "The Calling of St. Matthew".to_string()]);

    let x = &mut table; //create mutable reference
    let y = x; //do a copy by simply assigning to another variable?
    show(y);

}

Add show(x); after the the show(y); and watch what happens.

2 Likes

Ah i see that let y = x caused a transfer of ownership instead of a copy. How can i prove to myself that mutable reference is not a Copy type?

Something like this perhaps?

fn main() {
    let mut value = 23;
    takes_copy(&mut value);
}

fn takes_copy<T>(value: T)
where
    T: Copy,
{}

If you change it to pass &value instead of &mut value it will compile.

3 Likes

Awesome. Thanks

Note that while &mut T is not Copy, it may seem that sometimes it behaves like a Copy type:

fn consume(t: &mut i32) {
    //whatever
}
fn main() {
    let v: &mut i32 = unimplemented!();
    consume(v); // v moved into consume?
    consume(v); // but this still works
}

This works because built-in references have implicit reborrowing operation applied to them and this code desugars to:

consume(&mut *v);
consume(&mut *v);
5 Likes