I'm doing some exercises with using threads in Rust. I want to print chunked string, but I can't get pass lifetimes issue I've stumbled upon. Here's my code:
let input = "some sample string".to_string();
let mut threads = vec![];
for chunk in input.chars().collect::<Vec<char>>().chunks(2) {
threads.push(thread::spawn({
move || -> () {
println!("{:?}", chunk);
}
}))
}
When I'm trying to run it, I get a following error:
error[E0716]: temporary value dropped while borrowed
--> src\main.rs:7:18
|
7 | for chunk in input.chars().collect::<Vec<char>>().chunks(2) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^----------
| | |
| | temporary value is freed at the end of this statement
| creates a temporary which is freed while still in use
| argument requires that borrow lasts for `'static`
I understand that the compiler doesn't know if the chunk within the thread will not outlive the input
variable. But what I can do to fix this code?
I've tried to clone()
the vector, but it didn't help.