These are chat archives for rust-lang/rust

16th
Oct 2015
John C F
@critiqjo
Oct 16 2015 08:11

This code does't compile (due to move semantics of mutable references):

#[derive(Debug)]
struct Test;

fn main() {
    let mut a = Test;
    let b = &mut a;
    { let d = b; }
    println!("{:?}", b);
}

but these variants does:

    let mut a = Test;
    let b = &mut a;
    { let _ = b; } // the only change here
    println!("{:?}", b);

and

    let mut a = Test;
    let b = &mut a;
    fn try_move(z: &mut Test) { }
    try_move(b);
    println!("{:?}", b);

Why so?

Darius Clark
@dariusc93
Oct 16 2015 08:42
@critiqjo you could clone b
err
misread
panicbit
@panicbit
Oct 16 2015 09:56
@critiqjo Apparently, in the 2. example, you don't actually move b since you don't consume it in the let pattern.
In the 3. example Rust automatically reborrows the &mut for convenience. The function call is equivalent to try_move(&mut *b);.
John C F
@critiqjo
Oct 16 2015 18:24

since you don't consume it in the let pattern.

Ohh... Moves don't happen where _ is matched, huh?! Makes sense...

Rust automatically reborrows the &mut for convenience

Right! Otherwise, for instance, a Vec's &mut would become unusable after the first call to push, like:

let mut a = vec![4, 5];
let b = &mut a;
Vec::push(b, 6);
b.push(7);

Great! Thanks a lot @panicbit

panicbit
@panicbit
Oct 16 2015 18:29
I had to ask in #rust myself :smile:
John C F
@critiqjo
Oct 16 2015 18:34

:smile_cat:

Shouldn't this be documented somewhere... May be in rustonomicon, where internals are explained? (Though, I have yet to read it!)

panicbit
@panicbit
Oct 16 2015 18:36
I think this could still fit into the book. The 'nomicon is more for the dark arts of Rust ;)
"The Dark Arts of Advanced and Unsafe Rust Programming"
John C F
@critiqjo
Oct 16 2015 18:39
Hmm... The move behavior of &mut should definitely be in the book... Or, is it already there?
panicbit
@panicbit
Oct 16 2015 18:53
Well there are 3 chapters about ownership, which includes a chapter about lifetimes. The most important details are covered there, including why your 1. example did fail. The other two example cases are IMO not that important in comparison.
panicbit
@panicbit
Oct 16 2015 19:11
@critiqjo If you feel like it, you can add this to the book yourself. PRs are always welcome :)
John C F
@critiqjo
Oct 16 2015 20:00
It could fit in The Rules section, as a consequence of "exactly one mutable reference" rule. But wouldn't it be too much information for a beginner? Because it doesn't follow the normal move semantics with function calls.