What is the best way to dereference values within chains of iterators?

and*_*ett 9 iterator rust

当我使用迭代器时,我经常发现自己需要显式取消引用值。以下代码查找向量中所有元素对的总和:

extern crate itertools;

use crate::itertools::Itertools;

fn main() {
    let x: Vec<i32> = (1..4).collect();

    x.iter()
        .combinations(2)
        .map(|xi| xi.iter().map(|bar| **bar)
        .sum::<i32>())
        .for_each(|bar| println!("{:?}", bar));
}
Run Code Online (Sandbox Code Playgroud)

有没有比使用 a 更好的执行解除引用的方法map

更好的是无需显式取消引用即可执行这些类型的操作。

log*_*yth 8

使用xi.iter()意味着您明确要求对 中的值进行引用的迭代xi。由于在这种情况下您不需要引用而是需要实际值,因此您需要使用xi.into_iter()来获取值的迭代器。

所以你可以改变

.map(|xi| xi.iter().map(|bar| **bar).sum::<i32>())
Run Code Online (Sandbox Code Playgroud)

.map(|xi| xi.into_iter().sum::<i32>())
Run Code Online (Sandbox Code Playgroud)

游乐场链接

  • 不,您是否使用 `iter`、`iter_mut` 还是 `into_iter` 仅取决于您想要输出的类型。 (2认同)