我正在查看这个示例,以便在 Rust 中同时下载内容。
粗略地说,它看起来像这样:
#![feature(async_closure)]
use futures::{stream, StreamExt}; // 0.3.13
async fn foo() {
let xs_new = stream::once(async { 42 })
.map(async move |x| {
Some(x + 1)
})
.buffer_unordered(42);
}
Run Code Online (Sandbox Code Playgroud)
但是,我希望用来filter_map做这样的事情:
#![feature(async_closure)]
use futures::{stream, StreamExt}; // 0.3.13
async fn foo() {
let xs_new = stream::once(async { 42 })
.filter_map(async move |x| if x % 2 == 0 { Some(x + 1) } else { None })
.buffer_unordered(42);
}
Run Code Online (Sandbox Code Playgroud)
然而,这会失败并出现错误:“{integer} 不是 Future,该特征...未针对 {integer} 实现”。
有谁知道为什么filter_map失败但map工作正常?
buffer_unordered要求Item的 sStream本身就是Futures。map与闭包一起使用async是有效的,因为它将整数转换为Futures 并生成整数。
使用filter_map需要返回一个确定是否过滤的结果Future。但是,您忘记了通过使其返回来Option将整数转换为s :FutureSome(Future)
async fn foo() {
let xs_new = stream::once(async { 42 })
.filter_map(async move |x| {
if x % 2 == 0 {
Some(async move { x + 1 }) // <--------
} else {
None
}
})
.buffer_unordered(42);
}
Run Code Online (Sandbox Code Playgroud)