【发布时间】:2015-12-23 16:29:55
【问题描述】:
我无法编译这个程序:
use std::env;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let args: Vec<_> = env::args().skip(1).collect();
let (tx, rx) = mpsc::channel();
for arg in &args {
let t = tx.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(50));
let _new_arg = arg.to_string() + "foo";
t.send(arg);
});
}
for _ in &args {
println!("{}", rx.recv().unwrap());
}
}
我从命令行读取所有参数并模拟对线程中的每个参数做一些工作。然后我打印出这项工作的结果,这是我使用通道完成的。
error[E0597]: `args` does not live long enough
--> src/main.rs:11:17
|
11 | for arg in &args {
| ^^^^ does not live long enough
...
24 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
如果我理解得很好..args 的生命周期必须是static(即程序执行的整个时间),而它只存在于main 函数(?)的范围内。我不明白这背后的原因,以及如何解决它。
【问题讨论】:
标签: rust