我试图并行处理矢量中的元素。这是一个简化版本,它具有相同的错误消息:
use std::sync::mpsc;
use std::thread;
struct Delegate {
name: String,
}
impl Delegate {
fn new(name: String) -> Delegate {
Delegate { name: name }
}
fn present(&self, subject: &str) -> String {
let presentation = format!("{} presents {}.", self.name, subject);
presentation.to_owned()
}
}
struct Conference {
delegates: Vec<Delegate>,
}
impl Conference {
fn new(delegates: Vec<Delegate>) -> Conference {
Conference {
delegates: delegates,
}
}
fn run(&self) {
let (tx, rx) = mpsc::channel();
let iterator = self.delegates.iter();
for d in iterator {
let txd = mpsc::Sender::clone(&tx);
thread::spawn(move || {
let presentation = d.present("a resolution");
txd.send(presentation).unwrap();
});
}
for recieved in rx {
println!("{}", recieved);
}
}
}
fn main() {
let delegates = vec![
Delegate::new("Coldophia".to_owned()),
Delegate::new("Borginia".to_owned()),
Delegate::new("Khura'in".to_owned()),
];
let conference = Conference::new(delegates);
conference.run();
}
这是我得到的错误:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:32:39
|
32 | let iterator = self.delegates.iter();
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 30:5...
--> src/main.rs:30:5
|
30 | / fn run(&self) {
31 | | let (tx, rx) = mpsc::channel();
32 | | let iterator = self.delegates.iter();
33 | |
... |
44 | | }
45 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:32:24
|
32 | let iterator = self.delegates.iter();
| ^^^^^^^^^^^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:36:27: 39:14 d:&Delegate, txd:std::sync::mpsc::Sender<std::string::String>]` will meet its required lifetime bounds
--> src/main.rs:36:13
|
36 | thread::spawn(move || {
| ^^^^^^^^^^^^^
我不明白Rust在函数调用&#34;中的生命周期参数是什么意思,而且我不知道为什么它引用了函数定义中的匿名生命周期。还需要添加什么才能进行编译?