This code does not compile...
fn main() {
let data = "hi".to_string();
let wrap = &data;
std::thread::spawn(move || println!("{}", wrap));
}
...because data
doesn't live inside the spawned thread:
error[E0597]: `data` does not live long enough
--> src/main.rs:3:16
|
3 | let wrap = &data;
| ^^^^^ borrowed value does not live long enough
4 | std::thread::spawn(move || println!("{}", wrap));
| ------------------------------------------------ argument requires that `data` is borrowed for `'static`
5 | }
| - `data` dropped here while still borrowed
Why doesn't Rust move data
like it does wrap
? Is there any way to force data
to be moved along with with wrap
?
My real code looks more like this. I accept a message, parse it, and then send it to a thread for processing.
struct Message {
data: Vec<u8>,
}
let message = Message {
data: "{\"name\":\"Rust\"}".to_string(),
};
#[derive(Deserialize)]
struct Parsed<'a> {
name: &'a str,
}
let parsed: Parsed = serde_json::from_slice(&message.data).unwrap();
std::thread::Builder::new()
.name(parsed.name) // note: need some of the parsed data prior to moving into the thread...so cannot solve with JSON parsing inside thread
.spawn(move || println("{}", parsed.name));
I know I could modify my Parsed
struct to use String
s instead of &'a str
, but this reduces efficiency when the compiler should be able to move data
just fine.