[英]Rust: Lifetime outliving anonymous function
我正在嘗試使用函數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...
遇到這樣的錯誤first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 25:5...
我不確定什么生命比匿名生命更長久。 任何的想法?
apply_async
是一種采用&self
的方法。 這意味着self
是一個引用,它只能保證在調用apply_async
的持續時間內apply_async
。 關閉move || self.apply(datum)
move || self.apply(datum)
捕獲self
、lifetime 和所有內容,這意味着它不是'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_async
內重新實現apply
,例如:
fn apply_async(&self, datum: String) -> JoinHandle<String> {
let f = self.f;
return spawn(move|| f(datum));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.