标题应该已经提示您,我已经注意到How can I put an async function into a map in Rust?,并且我无法继续我的工作。以下是基于上述链接的示例代码:
extern crate async_std;
use async_std::task;
use std::future::Future;
use std::pin::Pin;
use std::boxed::Box;
type VarIn = &String;
type VarOut = String;
type FnType = Box< dyn Fn(VarIn) -> Pin<Box<dyn Future<Output=VarOut>>> >;
async fn test(v: FnType) {
println!("{}", v("hi".to_string()).await)
}
async fn var(s: &String) -> String {
format!("var:{}", s)
}
fn main() {
task::block_on(test(Box::new(|s| Box::pin(var(s)))));
}如果将VarIn替换为String而不是&String,那么一切都很好。然而,我的用例需要我传递一个引用来实现我的使用(我在无限循环中使用它,所以我不能将所有权传递给这个函数)。我应该怎么做才能成功地传递对异步函数的引用,或者有一些设计可以绕过这一点?
发布于 2020-07-25 06:23:30
您必须在函数测试中使用的类型定义中指定引用的生命周期以及它与Future的关系。
VarIn<'a> = &'a String;
VarOut = String;
FnType<'a> = Box<dyn Fn(VarIn<'a>) -> Pin<Box<dyn Future<Output=VarOut> + 'a>>>;这最终是行不通的,因为在test中创建的字符串将被放在函数的底部,而&String将随Future一起返回。您可以使用&str并让这个示例工作,这就是我建议的。
VarIn<'a> = &'a str
VarOut = String
FnType<'a> = Box<dyn Fn(VarIn<'a>) -> Pin<Box<dyn Future<Output=VarOut> + 'a>>>;https://stackoverflow.com/questions/63073942
复制相似问题