rust-lang / rust-lang/rust-clippy

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

Open
#12,644 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-enhancement L-suggestion
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating Clippy's existing map_flatten lint and its tests, then inspect how the current filter_map suggestion identifies match expressions. Add coverage for the pattern shown and define when a filter(matches!(...)) suggestion is valid; the lint tests should verify the emitted suggestion and avoid changing cases that are not equivalent.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.