andypea
andypea

Reputation: 1401

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

When I'm using iterators, I often find myself needing to explicitly dereference values. The following code finds the sum of all pairs of elements in a vector:

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

Is there a better way of performing the dereferencing than using a map?

Even better would be a way of performing these types of operations without explicitly dereferencing at all.

Upvotes: 9

Views: 5697

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161627

Using xi.iter() means that you are explicitly asking for an iterator of references to the values within xi. Since you don't want references in this case and instead want the actual values, you'd want to use xi.into_iter() to get an iterator for the values.

So you can change

.map(|xi| xi.iter().map(|bar| **bar).sum::<i32>())

to

.map(|xi| xi.into_iter().sum::<i32>())

Playground Link

Upvotes: 8

Related Questions