Skip to content

map_flatten could suggest filter(matches!()) in case of map( match { _ => Option }).flatten() #12644

Open
@matthiaskrgr

Description

@matthiaskrgr

Description

I hope this not too convoluted 😅

I came across some code like

.iter()
        .map(|n| match n {
            0 | 2 | 5 => Some(n),
            _ => None,
        })
        .flatten()

clippy already recognizes the pattern and filter_map fires:

help: try replacing `map` with `filter_map` and remove the `.flatten()`
   |
6  ~         .filter_map(|n| match n {
7  +             0 | 2 | 5 => Some(n),
8  +             _ => None,
9  +         })

but, I believe it would be more elegant to completely forgo the "map" as well as the "match" by using filter(.. matches!()) in case we find ourselves matching on a pattern:

        .iter()
        .filter(|n| matches!(n, 0 | 2 | 5,))
        .collect::<Vec<&i32>>();

Version

rustc 1.79.0-nightly (aa1c45908 2024-04-06)
binary: rustc
commit-hash: aa1c45908df252a5b0c14e1bcb38c6c55ae02efe
commit-date: 2024-04-06
host: x86_64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.2

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesL-suggestionLint: Improving, adding or fixing lint suggestions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions