Closed
Description
Quiz time! What do the following two programs do?
fn main() {
let mut x = 1;
let y = (0, &mut x);
fn foo((a, b): (int, &mut int)) {*b += a;}
foo(y);
foo(y);
}
fn main() {
let mut x = 1;
let y = &mut x;
fn foo(b: &mut int) {*b += 0;}
foo(y);
foo(y);
}
ANSWERS:
- The first program fails to compile at the second invocation of
foo
witherror: use of moved value: y
. - The second program compiles and runs fine.
This is because, apparently, a &mut
embedded in a tuple will make that tuple ineligible for implicit copyability, but a lone &mut
by itself can be implicitly copied till the cows come home.
I was very surprised at this behavior. And as far as I know, nowhere do we document these sorts of subtleties. This is bad. We can't have a coherent story on explaining unique pointers if we don't clearly lay out when a copy happens and when a move happens. Someone needs to write a reference.
Metadata
Metadata
Assignees
Labels
No labels