问题描述
我是并发新手。上下文是我生成一个在struct方法中使用具有生存期的方法的线程。然后我得到一个错误由于需求冲突而无法推断出适当的寿命
这是我的代码的简化示例。
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
如何避免此错误?是并发的反模式吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)