rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.98k stars 12.68k forks source link

Immutable reference can't be destructured from a mutable reference. #63132

Open purpleposeidon opened 5 years ago

purpleposeidon commented 5 years ago

Just a minor papercut & inconsistency. Playground:

// Motivating example.
let foo = &mut [0, 3, 2, 1];
foo.sort();
for &x in foo {
    println!("{}", x);
}

// Which of course doesn't work, because this doesn't work
let &_g = &mut 0;

// But this does!
fn f(_: &i32) {}
f(&mut 0);
RustyYato commented 5 years ago

Your last example is different because you are not destructuring anything. The unique reference is simply being coerced to a shared reference. In the first two examples coercion doesn't kick in because Rust thinks that it doesn't have enough type information to apply the coercion. Adding type annotations (let &_: &_ = &mut 0;) does make things compile. You can use let &mut x = &mut 0; to destructure unique references directly. This works in any pattern (match, for, etc.)