Optimized Clone of Copy Types?

Actually, going back to your given example, the lint is definitely correct (for generic types):

fn euclidean_distance(p1: &Point, p2: &Point) -> f32 {
    let p1 = p1.clone(); // unnecessary clone
    let p2 = p2.clone(); // unnecessary clone
    ((p2.x - p1.x).powf(2.0) + (p2.y - p1.y).powf(2.0)).sqrt()
}

The redundant_clone lint is telling you that you don't need to perform the clone at all, and could just use the borrowed value directly. If your type is not Copy and holds some allocation handle, you're needlessly cloning said allocation handle.

The lint it sounds like you're talking about is actually clone_on_copy, which does explicitly say why it's bad to call .clone() on a Copy type:

The only reason Copy types implement Clone is for generics, not for using the clone method on a concrete type.

(Or in other words, make a copy, not a clone, if you know that it is Copy. The reason is for clarity, not for performance.)


For the given example, clippy does in fact emit only clippy::clone_on_copy and not clippy::redundant_clone.

6 Likes