簡體   English   中英

rust 中 move 的語義是什么?

[英]What are the semantics of move in rust?

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
            println!("Inner counter: {}", Arc::strong_count(&counter));
        });
        handles.push(handle);

        // println!("Inter counter: {}", Arc::strong_count(&counter));
    }

    println!("Outer counter: {}", Arc::strong_count(&counter));

    for handle in handles {
        handle.join().unwrap();
    }

    println!(
        "Result: {}, {}",
        *counter.lock().unwrap(),
        Arc::strong_count(&counter)
    );
}

為什么Inner counterOuter counter都能輸出,但是Inter counter會報錯?

如果我取消注釋Inter counter ,銹編譯器會告訴我:

let counter: Arc<Mutex<i32>>
Go to Arc | Mutex

borrow of moved value: `counter`
value borrowed here after moverustcE0382
main.rs(10, 36): value moved into closure here
main.rs(11, 27): variable moved due to use in closure
main.rs(9, 13): move occurs because `counter` has type `Arc<Mutex<i32>>`, which does not implement the `Copy` trait

如果counter已經在theread::apawn的閉包內移動了,為什么外面仍然可以使用它?

我不確定這是否是由move關鍵字引起的。

如果 counter 已經在 theread::apawn 的閉包內移動了,為什么外面仍然可以使用它?

因為您有兩個名稱為counter的完全不同的變量:

    let counter = Arc::new(Mutex::new(0));

        let counter = Arc::clone(&counter);

第二個在閉包內得到move -d ,但第一個僅在迭代期間被借用以克隆它。

當第二個計數器被創建時,它會為循環體的其余部分遮蔽第一個計數器。 因此,您的代碼在語義上與以下內容相同:

    for _ in 0..10 {
        let counter2 = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter2.lock().unwrap();
            *num += 1;
            println!("Inner counter: {}", Arc::strong_count(&counter2));
        });
        handles.push(handle);

        println!("Inter counter: {}", Arc::strong_count(&counter2));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM