This simple function won't compile. Please help me understand why! (I'm still relatively new to Rust!)
fn foo<F: Fn() + Send>(f: F) {
thread::spawn(move || (f)() );
}
The full error is:
error[E0310]: the parameter type `F` may not live long enough
--> src/main.rs:7:5
|
7 | thread::spawn(move || f);
| ^^^^^^^^^^^^^^^^^^^^^^^^
| |
| the parameter type `F` must be valid for the static lifetime...
| ...so that the type `F` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound
|
5 | F: Fn() + Send + 'static,
| +++++++++
For more information about this error, try `rustc --explain E0310`.
(In my "real" code, I don't think I can use a 'static
lifetime.)
In my (limited) understanding, f
should be fully owned by the newly spawned thread. f
should be moved onto the thread's stack, and so should only have to live as long as the thread lives. So I don't understand the error!
This (even simpler!) code doesn't work either (with the same error):
fn foo<F: Send>(f: F) {
thread::spawn(move || f );
}
In contrast, something like this works fine:
fn foo(v: Vec<u8>) {
thread::spawn(move || v);
}
(For completeness, what I'm actually trying to do in my "real" code is more like this:)
fn foo<F: Fn(Context) + Send + Clone>(f: F) {
let mut handles = Vec::with_capacity(4);
for _ in 0..4 {
let context: Context = get_context();
let f_clone = f.clone();
let handle = thread::spawn(move || (f_clone)(context) );
handles.push(handle);
}
}