Skip to content

filter_map suggestion on flat_map is wrong #7050

Closed
@ghost

Description

Lint name: filter_map

I tried this code:

#![warn(clippy::filter_map)]

fn main() {
    let x = ["a", "abc", "abdc", "efg"];
    let c: String = x.iter()
        .filter(|s| s.starts_with('a'))
        .flat_map(|f| f.chars())
        .collect();       
   
    assert_eq!(c, "aabcabdc");
}

I expected to see this happen: no warning

Instead, this happened:

Checking playground v0.0.1 (/playground)
warning: called `filter(..).flat_map(..)` on an `Iterator`
 --> src/main.rs:5:21
  |
5 |       let c: String = x.iter()
  |  _____________________^
6 | |         .filter(|s| s.starts_with('a'))
7 | |         .flat_map(|f| f.chars())
  | |________________________________^
  |
note: the lint level is defined here
 --> src/main.rs:1:9
  |
1 | #![warn(clippy::filter_map)]
  |         ^^^^^^^^^^^^^^^^^^
  = help: this is more succinctly expressed by calling `.flat_map(..)` and filtering by returning `iter::empty()`
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#filter_map

warning: 1 warning emitted

This warning is special case of filter_map for flat_map that should be completely removed.

This suggestion is incorrect and can never work. The flat_map function must return a single type of iterator. It can't conditionally return iter::empty(). That won't compile.

Compiling playground v0.0.1 (/playground)
error[E0308]: `if` and `else` have incompatible types
  --> src/main.rs:17:17
   |
14 | /             if s.starts_with('a') {
15 | |                 s.chars()
   | |                 --------- expected because of this
16 | |             } else {
17 | |                 std::iter::empty()
   | |                 ^^^^^^^^^^^^^^^^^^ expected struct `Chars`, found struct `std::iter::Empty`
18 | |             }
   | |_____________- `if` and `else` have incompatible types
   |
   = note: expected type `Chars<'_>`
            found struct `std::iter::Empty<_>`

Playground

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions