rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.01k stars 1.48k forks source link

new lint: passthrough enumerate #12935

Open matthiaskrgr opened 2 weeks ago

matthiaskrgr commented 2 weeks ago

What it does

check for calls. enumerate() where the index is only passed through deeper down the iter chain without actually being used

Advantage

simpler code

Drawbacks

No response

Example

pub fn foo(x: Vec<Option<String>>) {
    let is = x
        .clone()
        .into_iter()
        .enumerate() // move form here
        .map(|(i, o)| (i, o.unwrap_or_default())) // "i" not used, only passed through
        .filter(|(_i, o)| o.len() > 3)
        .collect::<Vec<_>>();

    let could_be = x
        .into_iter()
        .map(|o| o.unwrap_or_default())
        .enumerate() // to here
        .filter(|(_i, o)| o.len() > 3)
        .collect::<Vec<_>>();
}
workingjubilee commented 2 weeks ago

drawbacks: if the lint is in any way incorrectly written it could fail to observe that the filter() function would reduce the number of items, or a flat_map could increase it, or so on, and the function would have changed results as a result of the moved enumerate().