我该如何应对懒惰的迭代器? [英] How do I cope with lazy iterators?
本文介绍了我该如何应对懒惰的迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在迭代器上使用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()
实际上未在此处调用. 书中对此警告进行了说明,但我不明白为什么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());
推荐答案
所链接的书说:
如果您尝试在迭代器上执行闭包以解决其副作用,请改用
for
.
这样,它就可以工作,而且对于阅读代码的人来说,这一点要清晰得多.要将向量转换为其他向量时,应使用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屋!
查看全文