rust-lang/rust-clippy

Lint for `fold` closure that never moves the accumulator

開放

#6,053 建立於 2020年9月16日

 (3 則留言) (0 個反應) (1 位負責人)Rust (1,391 個分叉)batch import
A-lintL-perfgood first issue

倉庫指標

星標
 (10,406 顆星)
PR 合併指標
 (平均合併 19天 22小時) (30 天內合併 113 個 PR)

描述

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 https://github.com/rust-lang/rust/issues/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);

貢獻者指南