I\'m having a hard time getting this to compile:
use std::thread::{self, JoinHandle};
struct Foo<\'c> {
foo: &\'c str,
}
impl<\'c> Foo&
The lifetime constraint that is causing this problem is the one in Thread::spawn
, which requires the FnOnce
closure to be Send
. Send
requires 'static
, which means that the data contains no non-'static
data. Your data, Foo
, contains a borrowed str
, which is not 'static
, which makes Foo
non-'static
. As a result, you can't send Foo
across threads.
Why is this? Since Foo
contains a borrow, it is valid for only a small lifetime. If Rust allowed you to send an instance of Foo
to another thread, then that thread could easily use Foo
long after the data it borrows has become invalid.
You might think that this is actually overly restrictive, and you'd be right. There's no reason to not allow local parallelism as long as you can prove to the borrow checker that the thread terminates within some lifetime. There are currently no constructs in Rust to do this, but there are some future solutions for this problem, such as this RFC which extends the Send
trait to allow local parallelism.