The Rust Programming Language says:
If you want to force the closure to take ownership of the values it uses in the environment, you can use the
move
keyword before the parameter list
What I have noticed with my code is that it won't take ownership of these values. The differences between my code and the given example are:
- using an integer instead of a
Vec
- making
x
mutable instead of immutable
Example 1: The Rust Programming Language
fn main() {
let x = vec![1, 2, 3];
let equal_to_x = move |z| z == x;
println!("can't use x here: {:?}", x);
let y = vec![1, 2, 3];
assert!(equal_to_x(y));
}
Example 2: My Code
fn main() {
let mut x = 1;
let equal_to_x = move |z| z == x;
println!("can use x here: {:?}", x);
let y = 1;
assert!(equal_to_x(y));
}
Why will example 2 compile but example 1 won't?
AWhy is the ownership of
x
not moved even if I explicitly writemove
in front of the closure? Why isx
accessible after moving it into the closure?