• Rust迭代器的适配器:take 和 take_while的用法
  • 发布于 2个月前
  • 232 热度
    0 评论
Iterator trait 中的 take 和 take_while 适配器可以在迭代了一定数量的项之后结束迭代,或是根据闭包来决定何时结束迭代。它们的签名如下:
// 堆代码 duidaima.com
fn take(self, n: usize) -> impl Iterator<Item=Self::Item>
    where Self: Sized;
fn take_while<P>(self, predicate: P) -> impl terator<Item=Self::Item>
    where Self: Sized, P: FnMut(&Self::Item) -> bool;
这两种迭代器都会获取迭代器的所有权,并返回一个新的迭代器,该迭代器从头开始返回各项,但可能会提前结束迭代。take 迭代器最多产生 n 个项,之后则返回 None。take_while 迭代器会对每个项执行 predicate,并在 predicate 第一次返回 false 时返回 None,之后每次调用 next 也会返回 None。

例如,在给定的电子邮件 message 中,邮件头 header 和正文之间有空行隔开,可以使用 take_while 只遍历邮件头:
let message = "To: jimb\r\n\
        From: superego <editor@oreilly.com>\r\n\
        \r\n\
        Did you get any writing done today?\r\n\
        When will you stop wasting time plotting fractals?\r\n";

for header in message.lines()
        .take_while(|l| !l.is_empty()) {
    println!("{}" , header);
}
Rust 的字符串字面量中,当字符串中的一行以反斜线结束时,不会包含字符串下一行的缩进。因此字符串中的任一行都没有前导空白。这意味着 message 的第三行是空白,take_while 适配器一看到这行空白就会终止迭代,继而这段代码只打印了前两行:
To: jimb
From: superego <editor@oreilly.com>

用户评论