I have a method where I pass in a reference as a parameter, and then move the reference into a thread and do some operation on it, which won't compile:
fn threaded_word_length(s: &str){
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
let i = s.len();
tx.send(i);
});
let length = rx.recv().unwrap();
println!("{}", length);
handle.join();
}
This gives the following error:
error[E0621]: explicit lifetime required in the type of `s`
--> src/main.rs:13:18
|
11 | fn threaded_word_length(s: &str){
| - consider changing the type of `s` to `&'static str`
12 | let (tx, rx) = mpsc::channel();
13 | let handle = thread::spawn(move || {
| ^^^^^^^^^^^^^ lifetime `'static` required
I'd agree with this error if the spawned thread were to be detached, and I didn't have any guarantee on when the thread would execute, but I am explicitly calling handle.join() afterwards here, so the reference variable s should be guaranteed to be valid for the lifetime of the spawned thread, no? Am I missing something, or is Rust not able to infer that the lifetime should be valid here?