为什么在if中添加分号可以避免借用检查错误?

时间:2018-04-27 15:57:42

标签: rust borrow-checker

我正在努力与借阅检查员。此代码无法编译:

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

fn main() {
    let counter = Arc::new(Mutex::new(0));
    {
        let clone = Arc::clone(&counter);
        thread::spawn(move || {
            if let Ok(mut v) = clone.lock() {
                *v = 10;
            }
        });
    }
}

错误讯息:

error[E0597]: `clone` does not live long enough
  --> src/main.rs:9:32
   |
9  |             if let Ok(mut v) = clone.lock() {
   |                                ^^^^^ borrowed value does not live long enough
...
12 |         });
   |         - `clone` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

如果我将;追加到if let,则代码会编译:

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

fn main() {
    let counter = Arc::new(Mutex::new(0));
    {
        let clone = Arc::clone(&counter);
        thread::spawn(move || {
            if let Ok(mut v) = clone.lock() {
                *v = 10;
            };  // <= append ";"
        });
    }
}

为什么前者无法编译?这是正确的行为吗?

我的环境:

rustc 1.27.0-nightly (ac3c2288f 2018-04-18)
binary: rustc
commit-hash: ac3c2288f9f9d977acb46406ba60033d65165a7b
commit-date: 2018-04-18
host: x86_64-apple-darwin
release: 1.27.0-nightly
LLVM version: 6.0

0 个答案:

没有答案