Skip to content
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 .cloned().filter() to suggest reverse #13594

Closed
GnomedDev opened this issue Oct 23, 2024 · 3 comments
Closed

Lint .cloned().filter() to suggest reverse #13594

GnomedDev opened this issue Oct 23, 2024 · 3 comments
Labels
A-lint Area: New lints

Comments

@GnomedDev
Copy link
Contributor

What it does

In an iterator chain, .cloned().filter() will lead to cloning items that are filtered out. This is wasteful and should be the other way around.

Advantage

Improves performance by cloning less.

Drawbacks

None to my knowledge.

Example

fn process_items<'a>(items: impl Iterator<Item = &Item>) -> ProcessedItems {
    items.cloned().filter(filter_item).map(process_item).collect()
}

Could be written as:

fn process_items<'a>(items: impl Iterator<Item = &Item>) -> ProcessedItems {
    items.filter(filter_item).cloned().map(process_item).collect()
}
@GnomedDev GnomedDev added the A-lint Area: New lints label Oct 23, 2024
@GnomedDev
Copy link
Contributor Author

Note: This is split from #3302

@y21
Copy link
Member

y21 commented Oct 23, 2024

This lint already exists: https://rust-lang.github.io/rust-clippy/master/index.html#iter_overeager_cloned

warning: unnecessarily eager cloning of iterator items
 --> src/lib.rs:8:5
  |
8 |     items.cloned().filter(filter_item).map(process_item).collect()
  |     ^^^^^-----------------------------
  |          |
  |          help: try: `.filter(|&x| filter_item(x)).cloned()`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#iter_overeager_cloned
  = note: `#[warn(clippy::iter_overeager_cloned)]` on by default

@GnomedDev
Copy link
Contributor Author

Got it.

@GnomedDev GnomedDev closed this as not planned Won't fix, can't repro, duplicate, stale Oct 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

2 participants