Skip to content

Lint against Iterator::map receiving a callable that returns () #106991

@estebank

Description

@estebank

Code

fn foo(items: &mut Vec<u8>){
    items.sort();
}

fn main() {
    let mut x: Vec<Vec<u8>> = vec![
        vec![0, 2, 1],
        vec![5, 4, 3],
    ];
    x.iter_mut().map(foo);
    println!("{x:?}");
}

Current output

Passes

Desired output

warning: `Iterator::map` call that discard the iterator's values
   |
LL | fn foo(items: &mut Vec<u8>) {
   |    --- this function returns `()`, which is likely not what you wanted
...
LL |     x.iter_mut().map(foo)
   |                  --- ^^^ called `Iterator::map` with callable that returns `()`
   |                  |
   |                  after this call to map, the resulting iterator is `impl Iterator<Item = ()>`, which means the only information carried by the iterator is the number of items
   |
   = note: `Iterator::map`, like many of the methods on `Iterator`, gets executed lazily, meaning that its effects won't be visible until it is iterated
help: you might have meant to use `Iterator::for_each`
   |
LL -     x.iter_mut().map(foo)
LL +     x.iter_mut().for_each(foo)
   |

Rationale and extra context

Mapping to () is almost always a mistake. The for_each suggestion should only be emitted if it would make sense with foo, like if it modifies the argument or has side-effects like printing or logging (the later would be hard to check for).

Other cases

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions