I'm new to Rust and trying to compile some lecture notes to help some students learn about the subject and I came across this in chapter 16 of the book: https://doc.rust-lang.org/book/ch16-01-threads.html . I'm running the example about spawning a thread with the vector where a closure takes place with a slight modification.
Here's the code I'm working with:
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
println!("{:?}", v);
}
I've added the last line println!("{:?}", v);
to the example. Without it, it is clear that v
may not live long enough, because the closure may outlive the current function. However, I expected that by adding a usage of v
after the join()
, that it would mean the compiler can reason that the vector v
must live past the join()
and therefore outlive the thread and its closure. Still, the compiler says error[E0373]: closure may outlive the current function, but it borrows
v, which is owned by the current function
Maybe that's incorrect, though? I thought about if I should open this as an issue in Github, but seeing that this forum exists I thought maybe I'd ask here first in case I'm overlooking something.
I'm working with Rust in macOS using 1.39.0 + CLion environment.