为什么涉及线程时必须使用“ move”关键字;为什么我不想要那种行为?

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

例如(取自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文档):let v = vec![1、2、3]; let handle = thread :: spawn(move || {println!(“这里是向量:{:?}”,v);});这不是关于什么动作的问题,而是...
multithreading concurrency rust move-semantics
2个回答
3
投票

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