This code compiles:
use std::thread;
struct Foo;
fn use_foo(foo: &Foo) {}
fn main() {
let foo = Foo {};
thread::spawn(move || {
use_foo(&foo);
});
}
but this code does not:
use std::thread;
struct Foo;
struct Bar<'a> {
foo: &'a Foo,
}
fn use_bar(bar: Bar) {}
fn main() {
let foo = Foo {};
let bar = Bar { foo: &foo };
thread::spawn(move || {
use_bar(bar);
});
}
Instead failing with
error[E0597]: `foo` does not live long enough
--> src/main.rs:15:26
|
15 | let bar = Bar { foo: &foo };
| ^^^^ borrowed value does not live long enough
16 | / thread::spawn(move || {
17 | | use_bar(bar);
18 | | });
| |______- argument requires that `foo` is borrowed for `'static`
19 | }
| - `foo` dropped here while still borrowed
This bears some similarity to this issue, however here there is only a single reference to foo
. Is there any way to get around this indirection introduced by bar
and move foo
into the closure?