我有一个通用的异步函数。我想用不同的类型调用它并并行运行结果 future 。但它似乎创建了不同类型的 future (尽管它们都是 impl Future
use std::fmt::Debug;
#[tokio::main]
async fn main() {
// both arguments to test function i32. Works.
let first = Box::pin(test(5));
let second = Box::pin(test(6));
futures::future::select_all(vec![first, second]).await;
}
async fn test<T: Debug>(x: T) {
async {
println!("{:?}", x);
}.await;
}
这行不通:
use std::fmt::Debug;
#[tokio::main]
async fn main() {
// one argument to test() is i32, the second argument is &str. Doesn't work
let first = Box::pin(test(5));
let second = Box::pin(test("five"));
futures::future::select_all(vec![first, second]).await;
}
async fn test<T: Debug>(x: T) {
async {
println!("{:?}", x);
}.await;
}
在我的具体示例中,我可以使用接受两个 future 的 select,但是如果我有很多 future 怎么办?如何选择多个不同类型的 future ?
最佳答案
你只需要稍微帮助编译器检测正确的类型。我们使用 dynamic dispatching在此处使用 dyn
关键字。
use std::fmt::Debug;
use std::pin::Pin;
#[tokio::main]
async fn main() {
// one argument to test() is i32, the second argument is &str.
let first = Box::pin(test(5));
let second = Box::pin(test("five"));
let v: Vec<Pin<Box<dyn futures::Future<Output = ()>>>> = vec![first, second];
futures::future::select_all(v).await;
}
async fn test<T: Debug>(x: T) {
async {
println!("{:?}", x);
}
.await;
}
所以我所做的就是将 Vector 提取到一个变量中并为其指定一个显式类型。
关于rust - 如何选择或加入不同类型的 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64331787/