This code does not compile for me and the error message isn't too helpful.
use std::thread;
fn main() {
let example = "abc\ndegf\nghijkl".to_string();
let mut handles = vec![];
for line in example.lines() {
handles.push(thread::spawn(move || {
return line.len();
}));
}
for handle in handles {
let length = handle.join().unwrap();
println!("Length: {}", length);
}
}
Compiler Error:
error[E0597]: `example` does not live long enough
--> src/main.rs:7:17
|
7 | for line in example.lines() {
| ^^^^^^^^^^^^^^^ borrowed value does not live long enough
8 | handles.push(thread::spawn(move || {
| ______________________-
9 | | return line.len();
10 | | }));
| |__________- argument requires that `example` is borrowed for `'static`
...
16 | }
| - `example` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` due to previous error
If I remove to_string it compiles and gives the expected result, I guess because then it's a string slice with static lifetime.
But even though I'm using a String above, I'm making sure to join all threads before main returns. So how can I show the compiler that the string lives long enough?