diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index c315b575ef59..aedbafd408b0 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -341,6 +341,9 @@ fn base_local_and_movability<'tcx>( let mut deref = false; // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509. let mut field = false; + // If projection is a slice index then clone can be removed only if the + // underlying type implements Copy + let mut slice = false; let PlaceRef { local, mut projection } = place.as_ref(); while let [base @ .., elem] = projection { @@ -348,9 +351,11 @@ fn base_local_and_movability<'tcx>( deref |= matches!(elem, mir::ProjectionElem::Deref); field |= matches!(elem, mir::ProjectionElem::Field(..)) && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty); + slice |= matches!(elem, mir::ProjectionElem::Index(..)) + && !is_copy(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty); } - Some((local, deref || field)) + Some((local, deref || field || slice)) } struct LocalUseVisitor { diff --git a/tests/ui/redundant_clone.fixed b/tests/ui/redundant_clone.fixed index 54815603c6de..b8faf4d253ad 100644 --- a/tests/ui/redundant_clone.fixed +++ b/tests/ui/redundant_clone.fixed @@ -160,3 +160,11 @@ fn not_consumed() { println!("{}", x); } } + +fn issue_5405() { + let a: [String; 1] = [String::from("foo")]; + let _b: String = a[0].clone(); + + let c: [usize; 2] = [2, 3]; + let _d: usize = c[1].clone(); +} diff --git a/tests/ui/redundant_clone.rs b/tests/ui/redundant_clone.rs index a9b31183adc8..9a24f68ecd0e 100644 --- a/tests/ui/redundant_clone.rs +++ b/tests/ui/redundant_clone.rs @@ -160,3 +160,11 @@ fn not_consumed() { println!("{}", x); } } + +fn issue_5405() { + let a: [String; 1] = [String::from("foo")]; + let _b: String = a[0].clone(); + + let c: [usize; 2] = [2, 3]; + let _d: usize = c[1].clone(); +} diff --git a/tests/ui/redundant_clone.stderr b/tests/ui/redundant_clone.stderr index 9c27812b9cdc..06c5560c94cb 100644 --- a/tests/ui/redundant_clone.stderr +++ b/tests/ui/redundant_clone.stderr @@ -167,5 +167,13 @@ note: cloned value is neither consumed nor mutated LL | let y = x.clone().join("matthias"); | ^^^^^^^^^ -error: aborting due to 14 previous errors +error: using `clone` on a `Copy` type + --> $DIR/redundant_clone.rs:169:21 + | +LL | let _d: usize = c[1].clone(); + | ^^^^^^^^^^^^ help: try removing the `clone` call: `c[1]` + | + = note: `-D clippy::clone-on-copy` implied by `-D warnings` + +error: aborting due to 15 previous errors