I am having issues passing command-line arguments into threads so have constructed this program which illustrates my issue.
use std::env;
use std::io::{self, Write};
use std::thread;
fn main() {
let stdout = io::stdout();
let args: Vec<String> = env::args().collect();
let arg = &args[1];
let thread = thread::spawn(move || {
writeln!(stdout.lock(), "argument was \"{}\"", arg).unwrap();
});
thread.join().unwrap();
}
However, the compiler gives me the following error when I try to compile this...
error[E0597]: `args` does not live long enough
--> main.rs:9:14
|
9 | let arg = &args[1];
| ^^^^ borrowed value does not live long enough
...
16 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
I am unsure as to how to compile a program like this. I understand the the &str
created by &args[1]
does not have a static lifetime so cannot be passed into the thread. However, what options are there for passing in program arguments into a thread?