I'm trying to process elements in a vector in parallel. This is a simplified version that has the same error message:
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();
}
This is the error I'm getting:
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 || {
| ^^^^^^^^^^^^^
I don't understand what Rust means by "lifetime parameter in function call", and I don't know why it refers to the anonymous lifetime on the function definition. What else do I need to add to get this to compile?