-
-
Notifications
You must be signed in to change notification settings - Fork 14.9k
Improve eagerly evaluating an iterator for its side-effects #44546
Copy link
Copy link
Closed
Labels
C-feature-acceptedCategory: A feature request that has been accepted pending implementation.Category: A feature request that has been accepted pending implementation.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
Metadata
Metadata
Assignees
Labels
C-feature-acceptedCategory: A feature request that has been accepted pending implementation.Category: A feature request that has been accepted pending implementation.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
Type
Fields
Give feedbackNo fields configured for issues without a type.
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
.collector.count(.for_eachis nightly only). Most beginners don't associate.countwith 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:
.collect's result#[must_use]. If you are throwing.collect's result away, you are doing it wrong, and should not have used.collectin the first place. A loop or.for_eachwould do..count's result#[must_use]: while.countis "efficent" (when compared to.collect) it doesn't convey what the code is actually doing.eval()==.for_each(|_|): because.for_each(|_|)is also ugly.collectmeans copy the results of the iterator into a collection, not "eagerly evaluate", or similar