使用select宏
select中使用的Future必須實(shí)現(xiàn)Unpin trait和FusedFuture trait。
必須實(shí)現(xiàn)unpin的原因是,select中使用的future不是按值獲取的,而是按照可變引用獲取的,通過不獲取future的所有權(quán),所以在調(diào)用select后,未完成的future可以繼續(xù)使用。
必須實(shí)現(xiàn)FusedFuture的原因,select完成后不會(huì)再輪詢future,因此需要實(shí)現(xiàn)FusedFuture來(lái)跟蹤future是否完成。
同樣的,對(duì)應(yīng)到stream上,會(huì)有一個(gè)FusedStream trait。
使用流的示例:
use futures::{
stream::{Stream, StreamExt, FusedStream},
select,
};
async fn add_two_streams(
mut s1: impl Stream<Item = u8> + FusedStream + Unpin,
mut s2: impl Stream<Item = u8> + FusedStream + Unpin,
) -> u8 {
let mut total = 0;
loop {
let item = select! {
x = s1.next() => x,
x = s2.next() => x,
complete => break,
};
if let Some(next_num) = item {
total += next_num;
}
}
total
}
其它
- Fuse::terminated()允許構(gòu)建一個(gè)已經(jīng)終止的空的Future;
- 當(dāng)需要同時(shí)運(yùn)行同一Future的多個(gè)副本時(shí),可以使用FuturesUnordered類型。