Closed
Description
With the following program:
use std::sync::Mutex;
pub fn main() {
let foo = Mutex::new(0u32);
if let Ok(foo) = foo.lock() {
println!("{}", foo);
}
}
I get the following compiler error:
error[E0597]: `foo` does not live long enough
--> src/main.rs:9:1
|
6 | if let Ok(foo) = foo.lock() {
| --- borrow occurs here
...
9 | }
| ^ `foo` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
However when I modify the program as follows:
use std::sync::Mutex;
pub fn main() {
let foo = Mutex::new(0u32);
if let Ok(foo) = foo.lock() {
println!("{}", foo);
}
{}
}
The program compiles and runs as expected.
It seems odd to me that inserting {}
after the lock
fixes the issue. It appears that any code following the lock
allows for the program to compile and run as expected, with an empty {}
or ()
being the simplest way of doing this.