如何解决使用具有生存期的方法生成线程时出错
我是并发新手。上下文是我生成一个在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 举报,一经查实,本站将立刻删除。