虽然已经太晚了,但我希望这段代码能帮助到其他人。在我的情况下,我有一些预定义的函数,我无法更改它们(func0,func1,...),我需要按顺序运行它们直到最后一个。如果其中一个失败,整个操作必须终止。因此,我创建了一个函数数组,然后在循环中执行每个函数。
use std::future::Future;
use std::pin::Pin;
type FuncResult = dyn Future<Output=Result<(), String>>;
async fn apply_funcs(mut start: usize, end: usize) {
let funcs = [func0];
let mut result = true;
while start < end && result {
result = func_wrapper(funcs[start]).await;
start += 1;
}
}
async fn func_wrapper(f: impl FnOnce() -> FuncResult) -> bool {
match f().await {
Ok(_) => { println!("ok"); }
Err(e) => {
println!("{e}");
return false;
}
}
true
}
async fn func0() -> Result<(), String> {
todo!()
}
这段代码失败了:
期望是dyn Future
,但找到的是future
我找到了两种解决方法:
1:通过静态分派,即通过泛型:
async fn apply_funcs(mut start: usize, end: usize) {
let funcs = [func0];
let mut result = true;
while start < end && result {
result = func_wrapper(funcs[start]).await;
start += 1;
}
}
async fn func_wrapper<Fut>(f: impl FnOnce() -> Fut) -> bool
where Fut: Future<Output=Result<(), String>> {
match f().await {
Ok(_) => { println!("ok"); }
Err(e) => {
println!("{e}");
return false;
}
}
true
}
async fn func0() -> Result<(), String> {
todo!()
}
2: 通过定义另一个闭包来实现动态调度:
type FuncResult = Pin<Box<dyn Future<Output=Result<(), String>>>>;
async fn apply_funcs(mut start: usize, end: usize) {
let funcs = [
|| -> FuncResult {
Box::pin(func0())
}
];
let mut result = true;
while start < end && result {
result = func_wrapper(funcs[start]).await;
start += 1;
}
}
async fn func_wrapper(f: impl FnOnce() -> FuncResult) -> bool {
match f().await {
Ok(_) => { println!("ok"); }
Err(e) => {
println!("{e}");
return false;
}
}
true
}
async fn func0() -> Result<(), String> {
todo!()
}