如何在futures :: Stream中使用take

编程入门 行业动态 更新时间:2024-10-17 09:46:30
本文介绍了如何在futures :: Stream中使用take_while?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试了解 take_while() 和futures::Stream;板条箱(0.1.25).这是一段代码(在操场上):

I'm trying to understand what syntax should I use for take_while() with futures::Stream; crate (0.1.25). Here's a piece of code (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()时,它会说

The main goal is to determine the right combinations of operators/commands to run the presented playground successfully with take_while: when I uncomment my take_while() it says

expected &i32, found integral variable | help: consider borrowing here: &10

如果我提供参考,它会说:

and if I put a reference, it says:

error[E0277]: the trait bound bool: futures::future::Future is not satisfied

对我来说很奇怪.

推荐答案

take_while期望闭包返回将来,或者可以将其转换为将来. bool没有实现IntoFuture,因此您必须将其包装在以后. future::ok 返回一个立即准备就绪的未来指定值.

take_while expects the closure to return a future, or something that can be converted to a future. bool doesn't implement IntoFuture, so you have to wrap it in a future instead. future::ok returns a future that is immediately ready with the specified value.

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:"); }

更多推荐

如何在futures :: Stream中使用take

本文发布于:2023-11-25 15:17:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   futures   Stream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!