Skip to content

Mutex giving dropped while still borrowed errors. #44801

Closed
@Mr-Byte

Description

@Mr-Byte

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions