Skip to content

Suggest removing filter_map for Iterator::filter_map(|x| Some(x)) #12556

Closed
@PartiallyUntyped

Description

@PartiallyUntyped

Summary

When we encounter a filter_map on what is effectively an identity function followed by Some, we shouldn't recommend map(identity), but we should instead recommend completely removing filter_map.

Many thanks to @Centri3 for finding this and #12501 .

Reproducer

I tried this code:

fn main() {
    let _= vec![Some(10), None].into_iter().filter_map(|x| Some(x));
}

What I saw:

    Checking playground v0.0.1 (/playground)
warning: this `.filter_map` can be written more simply using `.map`
 --> src/main.rs:4:12
  |
4 |     let _= vec![Some(10), None].into_iter().filter_map(|x| Some(x));
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
  = note: `#[warn(clippy::unnecessary_filter_map)]` on by default

warning: redundant closure
 --> src/main.rs:4:56
  |
4 |     let _= vec![Some(10), None].into_iter().filter_map(|x| Some(x));
  |                                                        ^^^^^^^^^^^ help: replace the closure with the function itself: `Some`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure
  = note: `#[warn(clippy::redundant_closure)]` on by default

warning: `playground` (bin "playground") generated 2 warnings (run `cargo clippy --fix --bin "playground"` to apply 1 suggestion)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.26s

What I expected to see:

    Checking playground v0.0.1 (/playground)
warning: this `.filter_map` for `|x| Some(x)` can be more succinctly written as
 --> src/main.rs:4:12
  |
4 |     let _= vec![Some(10), None].into_iter();
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
  = note: `#[warn(clippy::unnecessary_filter_map)]` on by default

This is a follow up from #12501's discussion.

Version

Latest Nightly on playground

Additional Labels

No response

Metadata

Metadata

Assignees

Labels

C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions