<分区>
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
我注意到我的代码不会拥有这些值的所有权。我的代码与给定示例之间的区别是:
- 使用整数代替
Vec
- 使
x
可变而不是不可变
示例 1:Rust 编程语言
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));
}
示例 2:我的代码
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));
}
为什么示例 2 会编译而示例 1 不会?
A即使我在闭包前面显式地写了
move
,为什么x
的所有权没有被移动?为什么x
移入闭包后可以访问?