我正在尝试使用函数 spawn
模拟异步执行但我无法编译下面的代码片段。
use std::thread::{spawn, JoinHandle};
fn main() {
let data = vec![String::from("some data"), String::from("some more data")];
let doer = Doer{f: |x| {return x + " hello"} };
let results: Vec<JoinHandle<String>> = data.iter()
.map(|x| doer.apply_async(x.to_owned()))
.collect();
results.iter().for_each(|x| println!("{}", x.join().unwrap()));
}
struct Doer {
f: fn(xs: String) -> String
}
impl Doer {
fn apply(&self, datum: String) -> String {
let f = &self.f;
return f(datum);
}
fn apply_async(&self, datum: String) -> JoinHandle<String> {
return spawn(move|| self.apply(datum));
}
}
我有这样的错误
first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 25:5...
我不确定什么生命比匿名生命更长久。
任何的想法?
最佳答案
apply_async
是一种需要 &self
的方法.这意味着 self
是一个引用,仅保证在对 apply_async
的调用期间有效.闭包move || self.apply(datum)
捕获 self
,生命周期和所有,这意味着它不是 'static
.这就是为什么你不能调用 spawn
在上面。
如 Doer
工具Clone
,解决此问题的一种方法是克隆 *self
和 move
它进入封闭。
fn apply_async(&self, datum: String) -> JoinHandle<String> {
let s = self.clone();
return spawn(move || s.apply(datum));
}
如果您不想克隆整个
Doer
,你只能复制必要的部分,然后重新实现 apply
内apply_async
, 例如: fn apply_async(&self, datum: String) -> JoinHandle<String> {
let f = self.f;
return spawn(move|| f(datum));
}
关于Rust:终生超越匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60018994/