일반적인 비동기 기능이 있습니다. 다른 유형으로 호출하고 결과 미래를 병렬로 실행하고 싶습니다. 그러나 그것은 다른 유형의 미래를 생성하는 것처럼 보입니다 (모두가 impl Future <Output = ()> 임에도 불구하고), 따라서 Vector에 다른 유형의 객체를 넣을 수 없으므로 select 함수를 호출 할 수 없습니다. 내가 의미하는 바는 다음과 같습니다.
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;
}
구체적인 예에서는 두 개의 선물을받는 select를 사용할 수 있지만, 선물이 많은 경우 어떻게해야합니까? 유형이 다른 여러 선물을 어떻게 선택할 수 있습니까?
컴파일러가 올바른 유형을 감지하도록 도와 주면됩니다. 여기서는 키워드 와 함께 동적 디스패치 를 사용 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를 변수로 추출하고 명시적인 유형을 지정하는 것입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다