`move ||` 成语的目的是什么?
What is the purpose of the `move ||` idiom?
Rust docs里面有一个关于并发的学习练习,代码如下:
let philosophers = vec![
Philosopher::new("Judith Butler"),
Philosopher::new("Gilles Deleuze"),
Philosopher::new("Karl Marx"),
Philosopher::new("Emma Goldman"),
Philosopher::new("Michel Foucault"),
];
let handles: Vec<_> = philosophers.into_iter().map(|p| {
thread::spawn(move || {
p.eat();
})
}).collect();
for h in handles {
h.join().unwrap();
}
他们简要解释了其中的每一部分,但没有解释为什么 move
指令和 thread::spawn()
调用中的逻辑或:
This closure needs an extra annotation, move, to indicate that the closure is going to take ownership of the values it’s capturing.
但是,这个 'annotation' 看起来与其他注释(例如类型)完全不同。这里到底发生了什么,为什么? (搜索该代码片段似乎没有指向任何地方,而是关于其他类型 move
ing 的相同文档和其他博客文章。)
通过引用捕获的闭包具有 |ARGUMENTS| EXPRESSION
.
形式
按值捕获的闭包具有 move |ARGUMENTS| EXPRESSION
.
形式
move
是目前仅在该位置使用的关键字。
有点不幸的是,不接受参数的闭包看起来像逻辑 OR 运算符,但事实就是如此。它没有语法歧义。
Rust docs里面有一个关于并发的学习练习,代码如下:
let philosophers = vec![
Philosopher::new("Judith Butler"),
Philosopher::new("Gilles Deleuze"),
Philosopher::new("Karl Marx"),
Philosopher::new("Emma Goldman"),
Philosopher::new("Michel Foucault"),
];
let handles: Vec<_> = philosophers.into_iter().map(|p| {
thread::spawn(move || {
p.eat();
})
}).collect();
for h in handles {
h.join().unwrap();
}
他们简要解释了其中的每一部分,但没有解释为什么 move
指令和 thread::spawn()
调用中的逻辑或:
This closure needs an extra annotation, move, to indicate that the closure is going to take ownership of the values it’s capturing.
但是,这个 'annotation' 看起来与其他注释(例如类型)完全不同。这里到底发生了什么,为什么? (搜索该代码片段似乎没有指向任何地方,而是关于其他类型 move
ing 的相同文档和其他博客文章。)
通过引用捕获的闭包具有 |ARGUMENTS| EXPRESSION
.
按值捕获的闭包具有 move |ARGUMENTS| EXPRESSION
.
形式
move
是目前仅在该位置使用的关键字。
有点不幸的是,不接受参数的闭包看起来像逻辑 OR 运算符,但事实就是如此。它没有语法歧义。