Rust线程中是否需要“ move”关键字?

问题描述 投票:4回答:2

我一直在想,为什么在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。 :)


我一直在想,为什么在Rust中使用move关键字是必要的。例如(取自Rust文档):let v = vec![1、2、3];让句柄= thread :: spawn(move || {println!(“ ...
multithreading concurrency rust move-semantics
2个回答
2
投票

1
投票
© www.soinside.com 2019 - 2024. All rights reserved.