Silence redundant clone suggestion

This commit is contained in:
Esteban Küber 2024-03-13 05:46:53 +00:00
parent 065454dd1d
commit 01b810e052
4 changed files with 25 additions and 5 deletions

View file

@ -1027,6 +1027,11 @@ fn suggest_cloning_inner(
span: Span,
) {
let tcx = self.infcx.tcx;
if let Some(_) = self.clone_on_reference(expr) {
// Avoid redundant clone suggestion already suggested in `explain_captures`.
// See `tests/ui/moves/needs-clone-through-deref.rs`
return;
}
// Try to find predicates on *generic params* that would allow copying `ty`
let suggestion =
if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) {

View file

@ -0,0 +1,18 @@
//@ run-rustfix
#![allow(dead_code, noop_method_call)]
use std::ops::Deref;
struct S(Vec<usize>);
impl Deref for S {
type Target = Vec<usize>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl S {
fn foo(&self) {
// `self.clone()` returns `&S`, not `Vec`
for _ in <Vec<usize> as Clone>::clone(&self).into_iter() {} //~ ERROR cannot move out of dereference of `S`
}
}
fn main() {}

View file

@ -1,3 +1,4 @@
//@ run-rustfix
#![allow(dead_code, noop_method_call)]
use std::ops::Deref;
struct S(Vec<usize>);

View file

@ -1,5 +1,5 @@
error[E0507]: cannot move out of dereference of `S`
--> $DIR/needs-clone-through-deref.rs:14:18
--> $DIR/needs-clone-through-deref.rs:15:18
|
LL | for _ in self.clone().into_iter() {}
| ^^^^^^^^^^^^ ----------- value moved due to this method call
@ -12,10 +12,6 @@ help: you can `clone` the value and consume it, but this might not be your desir
|
LL | for _ in <Vec<usize> as Clone>::clone(&self).into_iter() {}
| ++++++++++++++++++++++++++++++ ~
help: consider cloning the value if the performance cost is acceptable
|
LL | for _ in self.clone().clone().into_iter() {}
| ++++++++
error: aborting due to 1 previous error