我在将命令行参数传递给线程时遇到问题,因此构建了说明我问题的程序。
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();
}
但是,当我尝试编译此文件时,编译器给我以下错误...
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...
我不确定如何编译这样的程序。我了解由&str
创建的&args[1]
没有静态生存期,因此无法传递到线程中。但是,有什么选项可以将程序参数传递给线程?