-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Lint .iter().for_each() #6543
Comments
One downside is that |
@llogiq I think the intention is to only lint |
Yes, camsteffen is right. Actually, with the criteria I wrote above, the normal usage of // doesn't lint
collection.iter().chain(...).for_each(...); The two situations in which it does falsely lint are these: let temp = collection.iter();
temp.chain(&collection2).for_each(...); impl MyCollection {
pub fn iter(&self) -> impl Iterator<Item = MyType> {
// returning a chaining iterator as impl Iterator from a method
self.collection.iter().chain(&self.collection2)
}
}
my_collection.iter().for_each(...); I think both of these patterns are somewhat exotic. It's probably unlikely that false positives from this lint will be a problem in practice. If it does turn out to be a problem, the lint can be further restricted to only trigger when |
Good points. Actually I think returning |
I'm working on it! |
Please note that any |
Good point! Thanks! |
New Lint: needless_for_each resolves: #6543 changelog: Added pedantic lint: `needless_for_each`
What it does
A thing I see really often is beginners attempting to embrace functional style programming by replacing all for-loops with
collection.iter().for_each(|item| ...)
. Because this happens so often, it might be beneficial to introduce a clippy lint to reassure those people that there's nothing wrong with the traditional for-loop.This lint would be triggered when the following criteria match:
foo.method()
matches,make_foo().method()
doesn't. That's because long iterator chains ending with for_each should not trigger this lint)vec.iter().for_each(process)
should not trigger because the alternative is (arguably) inferior:for item in &vec { process(item) }
)Categories (optional)
clippy::complexity
What is the advantage of the recommended code over the original code
The code is easier to digest than the syntax-heavy for_each with the embedded closure.
Drawbacks
None.
Example
Could be written as:
The text was updated successfully, but these errors were encountered: