4

I'm struggling with the borrow checker. This code fails to compile:

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 message:

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 I append ; to if let, the code compiles:

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 ";"
        });
    }
}

Why does the former fail to compile? Is it correct behavior?

My environment:

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
tanagumo
  • 383
  • 1
  • 8
  • 5
    I think this is the same problem as [When returning the outcome of consuming a StdinLock, why was the borrow to stdin retained?](https://stackoverflow.com/q/43590162/155423). TL;DR we think it's a bug, but don't know exactly where. Non-lexical lifetimes fixes it. Note that the linked issue matches well: [There are a number of situations where a trailing expression like a for-loop ends up being treated by the region lifetime inferencer as requiring a much longer lifetime assignment than what you would intuitively expect.](https://github.com/rust-lang/rust/issues/21114) – Shepmaster Apr 27 '18 at 16:09

0 Answers0