我如何应对惰性迭代器? [英] How do I cope with lazy iterators?

查看:16
本文介绍了我如何应对惰性迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 map() 在迭代器上对数组进行排序.

I'm trying to sort an array with a map() over an iterator.

struct A {
    b: Vec<B>,
}

#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct B {
    c: Vec<i32>,
}

fn main() {
    let mut a = A { b: Vec::new() };

    let b = B { c: vec![5, 2, 3] };
    a.b.push(b);

    a.b.iter_mut().map(|b| b.c.sort());
}

给出警告:

warning: unused `std::iter::Map` that must be used
  --> src/main.rs:16:5
   |
16 |     a.b.iter_mut().map(|b| b.c.sort());
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: #[warn(unused_must_use)] on by default
   = note: iterators are lazy and do nothing unless consumed

这是真的,sort() 实际上并没有在这里调用.book 中描述了这个警告,但是我不明白为什么 iter_mut() 的这种变体可以正常工作:

Which is true, sort() isn't actually called here. This warning is described in the book, but I don't understand why this variation with iter_mut() works fine:

a.b.iter_mut().find(|b| b == b).map(|b| b.c.sort());

推荐答案

正如你链接到的书所说:

As the book you linked to says:

如果您尝试在迭代器上执行闭包以获得其副作用,请改用 for.

If you are trying to execute a closure on an iterator for its side effects, use for instead.

这样就可以了,任何阅读代码的人都会更清楚.当你想将一个向量转换成不同的向量时,你应该使用 map.

That way it works, and it's much clearer to anyone reading the code. You should use map when you want to transform a vector to a different one.

这篇关于我如何应对惰性迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆