Skip to content

Adding method to consume an iterator efficiently #64117

Description

@Phosphorus15

Currently, mapping methods for iterator, e.g. map and filter are implemented in a lazy manner. Which means they would not be calculated until further consumption.
However, sometimes it can be the case that given an Iterator (whatever it actually is) . we just wanted its side-effect and to simply consume it. for instance :

#[derive(Debug)]
struct Item(i32);

fn take_iter<T : Iterator>(iter: T) {
    // we just want to consume the `iter` here
    // do something else
}

fn main() {
    let ve = vec![Item(1), Item(2), Item(3), Item(1)];

    take_iter(ve.iter().filter(|value| value.0 < 3).map(|value| {
        println!("{:?}", value);
        value
    }));
}

Currently, there're several ways of achieving this goal, for example :

fn take_iter<T : Iterator>(iter: T) {
    iter.for_each(|_| {}); // consumed
     // do something else
}
fn take_iter<T : Iterator>(iter: T) {
    iter.count(); // consumed
    // do something else
}

While they're both usable, it's obvious that these methods are at the cost of efficiency, for_each yields a call to closure which is totally unnecessary, while count finally counting the number of elements in vain.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-api[DEPRECATED; DO NOT USE]

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions