在下面的代码中,如果我注释掉println!
匹配表达式后的语句,就会出现借用检查器相关的问题。为了解决这个问题,编译器要求我在表达式末尾添加一个分号,match
这解决了这个问题,但我不明白这样做的必要性。
use std::sync::{Arc, Mutex};
#[derive(Default)]
struct A {
b: Arc<Mutex<B>>,
}
#[derive(Default)]
struct B {
c: Arc<Mutex<C>>,
}
#[derive(Default)]
struct C {
d: i32,
}
fn main() {
let a = A::default();
match a.b.lock().unwrap().c.lock().unwrap().d {
0 => println!("zero"),
_ => println!("non-zero"),
}
// uncommenting the below line makes borrow checker happy
// println!("{}", a.b.lock().unwrap().c.lock().unwrap().d);
}
错误
error[E0597]: `a.b` does not live long enough
--> src/main.rs:21:11
|
19 | let a = A::default();
| - binding `a` declared here
20 |
21 | match a.b.lock().unwrap().c.lock().unwrap().d {
| ^^^----------------
| |
| borrowed value does not live long enough
| a temporary with access to the borrow is created here ...
...
27 | }
| -
| |
| `a.b` dropped here while still borrowed
| ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `MutexGuard`
|
help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped
|
24 | };
| +
For more information about this error, try `rustc --explain E0597`.
他们在 2024 年版中对其进行了更改。
您可以在操场上尝试,如果您使用夜间版本,它可以编译但不能在稳定版本上进行。
https://doc.rust-lang.org/nightly/edition-guide/rust-2024/temporary-tail-expr-scope.html