Lifetime errors for referenced objects when reference is moved are not clear
I believe there is room for improvement here:
use std::path::{Path,PathBuf};
use std::thread;
fn main() -> () {
let pb = PathBuf::from(".");
let p = Path::new(&pb);
thread::spawn(move|| {
println!("{:?}", p);
});
}
This is obviously not correct, since p depends on pb which may not live as long, now that pb has been moved to the thread's scope and shares its lifetime.
However, the error when compiling this is problematic, since it doesn't make it clear at all why this object's lifetime needs to be increased:
> rustc +nightly ./test.rs
error[E0597]: `pb` does not live long enough
--> ./test.rs:6:24
|
6 | let p = Path::new(&pb);
| ^^ does not live long enough
...
10 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
error: aborting due to previous error
It's easy to imagine a case where it's not as simple to figure out what is going on (perhaps a chain of references, separated by hundreds of lines of code, that compiled just fine until one of these latter references was moved to spawn a thread, and suddenly the lifetime of a completely different variable in code that wasn't touched is throwing an error).
Current output:
error[E0597]: `pb` does not live long enough --> src/main.rs:6:23 | 6 | let p = Path::new(&pb); | ----------^^^- | | | | | borrowed value does not live long enough | argument requires that `pb` is borrowed for `'static` ... 10 | } | - `pb` dropped here while still borrowedEsteban Kuber at 2020-02-14 09:36:12
Current output:
error[E0597]: `pb` does not live long enough --> src/main.rs:6:23 | 5 | let pb = PathBuf::from("."); | -- binding `pb` declared here 6 | let p = Path::new(&pb); | ^^^ borrowed value does not live long enough 7 | / thread::spawn(move|| { 8 | | println!("{:?}", p); 9 | | }); | |______- argument requires that `pb` is borrowed for `'static` 10 | } | - `pb` dropped here while still borrowedEsteban Kuber at 2023-10-20 19:48:31
@estebank is it fixed, though? Ideally the error message would mention
pMahmoud Al-Qudsi at 2023-10-20 20:14:01
Sure, we can leave it open to address that part.
Esteban Kuber at 2023-10-20 22:20:18