Skip to content

Improve eagerly evaluating an iterator for its side-effects #44546

Description

@mattico

0b_0101_001_1010 had a good idea on Reddit. I'll paraphrase it here.

The only way to eagerly consume an iterator, e.g., for its side-effects, on stable Rust is to call .collect or .count (.for_each is nightly only). Most beginners don't associate .count with this, so they use .collect, which is horrible.

There are a few things we could do to help make it more obvious what the correct thing to do is:

  • make .collect's result #[must_use]. If you are throwing .collect's result away, you are doing it wrong, and should not have used .collect in the first place. A loop or .for_each would do.
  • make .count's result #[must_use]: while .count is "efficent" (when compared to .collect) it doesn't convey what the code is actually doing
  • add an .eval() == .for_each(|_|): because .for_each(|_|) is also ugly
  • address this in docs: .collect means copy the results of the iterator into a collection, not "eagerly evaluate", or similar

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-acceptedCategory: A feature request that has been accepted pending implementation.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