Skip to content

Lint for fold closure that never moves the accumulator #6053

Open
@scottmcm

Description

@scottmcm

What it does

Lint when a fold closure always returns the accumulator from the input, having only used it by reference. (As opposed to consuming the accumulator, or returning something else.)

Categories (optional)

  • Kind: perf

The compiler currently cannot always optimize away passing along the accumulator every time (see rust-lang/rust#76725), so it's better to not do that if it's actually the same thing every time anyway.

Drawbacks

None.

(Well, it leaves something mut, but that's easily fixable with let v = v;.)

Example

    let word = word.to_lowercase();
    let char_count: HashMap<char, usize> = word.chars().fold(HashMap::new(), |mut chars, c| {
        *chars.entry(c).or_default() += 1;
        chars
    });

Could be written as:

    let word = word.to_lowercase();
    let mut char_count: HashMap<char, usize> = HashMap::new();
    word.chars().for_each(|c| *chars.entry(c).or_default() += 1);

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsL-perfLint: Belongs in the perf lint groupgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions