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.4k stars 1.54k forks source link

clone().iter_mut() is rarely what you want #11177

Open steventrouble opened 1 year ago

steventrouble commented 1 year ago

What it does

This lint warns you when you've called .clone().iter_mut() without saving the result anywhere.

You rarely want to mutate a cloned value without first saving the data somewhere. You can't access the data if it's not stored in a variable, so mutating it would be a noop.

Advantage

Drawbacks

Example

fn add_one(a : &mut Vec<usize>) {
    for x in a.clone().iter_mut() {
        // oops, this does nothing
        *x += 2;
    }
}

Could be written as:

fn add_one(a : &mut Vec<usize>) {
    for x in a.iter_mut() {
        *x += 2;
    }
}

fn added_one(a : &Vec<usize>) -> Vec<usize> {
    // no need for it to be mutable
    a.clone().iter_mut().map(|&mut x| x + 1).collect()
}

Could be written as:

fn added_one(a : &Vec<usize>) -> Vec<usize> {
    a.iter().map(|&x| x + 1).collect()
}
Centri3 commented 1 year ago

Could probably lint stuff like vec![1, 2].clone().get_mut() as well