我试图了解在futures::Stream;
板条箱(0.1.25)中对take_while()
使用什么语法。这是一段代码(on playground):
use futures::{stream, Stream}; // 0.1.25
fn into_many(i: i32) -> impl Stream<Item = i32, Error = ()> {
stream::iter_ok(0..i)
}
fn main() {
println!("start:");
let _ = into_many(10)
// .take_while(|x| { x < 10 })
.map(|x| {
println!("number={}", x);
x
})
.wait();
for _ in foo {} // ← this (by @mcarton)
println!("finish:");
}
主要目标是确定操作员/命令的正确组合,以使用take_while
成功运行展示的游乐场:当我取消注释take_while()时,它说
expected &i32, found integral variable | help: consider borrowing here: &10
如果我提供参考,它会说:
error[E0277]: the trait bound bool: futures::future::Future is not satisfied
对我来说很奇怪。
答案 0 :(得分:2)
take_while
期望闭包返回将来,或者可以转换为将来的东西。 bool
没有实现IntoFuture
,因此您将来必须将其包装。 future::ok
返回具有指定值的立即准备好的未来。
use futures::{future, stream, Stream}; // 0.1.25
fn into_many(i: i32) -> impl Stream<Item = i32, Error = ()> {
stream::iter_ok(0..i)
}
fn main() {
println!("start:");
let foo = into_many(10)
.take_while(|&x| { future::ok(x < 10) })
.map(|x| {
println!("number={}", x);
x
})
.wait();
for _ in foo {}
println!("finish:");
}
答案 1 :(得分:1)
wait
返回流的迭代器版本,但是该迭代器仍然是惰性的,这意味着您需要对其进行迭代以实际执行关闭操作:
use futures::{stream, Stream}; // 0.1.25
fn into_many(i: i32) -> impl Stream<Item = i32, Error = ()> {
stream::iter_ok(0..i)
}
fn main() {
println!("start:");
let foo = into_many(10)
// .take_while(|x| { x < 10 })
.map(|x| {
println!("number={}", x);
x
})
.wait();
for _ in foo {} // ← this
println!("finish:");
}