rust-lang / rust-lang/rust-clippy

Move data outside of `.filter_map` and false positve `unnecessary_filter_map`

Open
#9,211 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

Clippy propose to use .filter instead of .filter_map but in .filter we have an item reference while in .filter_map item itself and can move this item to some outside variable.

Lint Name

unnecessary_filter_map

Reproducer

I tried this code:

fn main() {
    let mut vec = vec![];
    let data = (0..10)
        .collect::<Vec<_>>()
        .into_iter()
        .filter_map(|v| {
            if v % 2 == 0 {
                vec.push(v);
                None
            } else {
                Some(v)
            }
        })
        .collect::<Vec<_>>();
    println!("{:?} {:?}", vec, data);
}

I saw this happen:

    Checking playground v0.0.1 (/playground)
warning: this `.filter_map` can be written more simply using `.filter`
  --> src/main.rs:3:16
   |
3  |       let data = (0..10)
   |  ________________^
4  | |         .collect::<Vec<_>>()
5  | |         .into_iter()
6  | |         .filter_map(|v| {
...  |
12 | |             }
13 | |         })
   | |__________^
   |
   = note: `#[warn(clippy::unnecessary_filter_map)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map

warning: `playground` (bin "playground") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.36s

I expected to see this happen:

Version
rustc 1.64.0-nightly (f8588549c 2022-07-18)
binary: rustc
commit-hash: f8588549c3c3d45c32b404210cada01e2a45def3
commit-date: 2022-07-18
host: x86_64-unknown-linux-gnu
release: 1.64.0-nightly
LLVM version: 14.0.6
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 the unnecessary_filter_map lint and reproduce the reported Rust example. Check how the lint handles closures that move items into an outside variable, then add coverage for this case and verify the false-positive warning is gone without changing valid lint behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.