rust-lang / rust-lang/rust-clippy
`map_flatten` could suggest `filter(matches!())` in case of `map( match { _ => Option }).flatten()`
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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