我一直在想,为什么在Rust中使用move
关键字是必要的。例如(取自the Rust docs):
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("Here's a vector: {:?}", v);
});
这不是关于[[what move
的问题,而是关于为什么必须指定的问题。
[如果您希望闭包获得外部值的所有权
,是否有理由不使用move
关键字?如果在这些情况下始终要求move
,是否有任何理由不能仅仅隐含/忽略move
的存在?例如:let v = vec![1, 2, 3];
let handle = thread::spawn(/* move is implied here */ || {
// Compiler recognizes that `v` exists outside of this closure's
// scope and does black magic to make sure the closure takes
// ownership of `v`.
println!("Here's a vector: {:?}", v);
});
上面的示例给出了以下编译错误:closure may outlive the current function, but it borrows `v`, which is owned by the current function
当错误仅通过添加
move
而神奇地消失时,我不禁对自己感到奇怪:为什么我not想要那种行为?
我并不是说所需的语法有什么问题。我只是想从比我更了解Rust的人们那里更深入地了解move
。 :)