I'm a newbie of concurrency. The context is I spawn a thread that using a method with a lifetime in a struct method. Then I got an error cannot infer an appropriate lifetime due to conflicting requirements
Here is a simplified example of my code.
use std::thread;
use std::time::Duration;
struct Printer{
prefix: &'static str,
}
impl Printer {
pub fn print(&self, text: String) {
println!("{}: {}", self.prefix, text);
}
pub fn new(prefix: &'static str) -> Self {
Printer {
prefix: prefix
}
}
}
struct Foo<'a> {
printer: &'a Printer
}
impl<'a> Foo<'a> {
fn pop(&self) {
thread::spawn(|| {
self.printer.print(String::from("pop"));
});
}
pub fn new(printer: &'a Printer) -> Self {
Foo {
printer: printer
}
}
}
fn main() {
let printer = Printer::new("freaking");
printer.print(String::from("hell"));
let foo = Foo::new(&printer);
foo.pop();
}
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:28:23
|
28 | thread::spawn(|| {
| _______________________^
29 | | self.printer.print(String::from("pop"));
30 | | });
| |_________^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 26:6...
--> src/main.rs:26:6
|
26 | impl<'a> Foo<'a> {
| ^^
note: ...so that the types are compatible
--> src/main.rs:28:23
|
28 | thread::spawn(|| {
| _______________________^
29 | | self.printer.print(String::from("pop"));
30 | | });
| |_________^
= note: expected `&&Foo<'_>`
found `&&Foo<'a>`
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:28:23: 30:10 self:&&Foo<'_>]` will meet its required lifetime bounds
--> src/main.rs:28:9
|
28 | thread::spawn(|| {
| ^^^^^^^^^^^^^
error: aborting due to previous error
How could I avoid this error? Is it an anti-pattern for concurrency?