Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing Clone implementation leads to mysterious errors down the line #91532

Closed
jimblandy opened this issue Dec 4, 2021 · 1 comment · Fixed by #118076
Closed

Missing Clone implementation leads to mysterious errors down the line #91532

jimblandy opened this issue Dec 4, 2021 · 1 comment · Fixed by #118076
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@jimblandy
Copy link
Contributor

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0fc37a6dfe3b8c2232f2b4eb2ab8615c

struct Board;

fn do_part1(boards: &Vec<Board>) {
    let mut boards = boards.clone();
    boards[0] = Board;
}

The current output is:

warning: variable does not need to be mutable
 --> src/lib.rs:4:9
  |
4 |     let mut boards = boards.clone();
  |         ----^^^^^^
  |         |
  |         help: remove this `mut`
  |
  = note: `#[warn(unused_mut)]` on by default

error[E0596]: cannot borrow `*boards` as mutable, as it is behind a `&` reference
 --> src/lib.rs:5:5
  |
4 |     let mut boards = boards.clone();
  |         ---------- help: consider changing this to be a mutable reference: `&mut Vec<Board>`
5 |     boards[0] = Board;
  |     ^^^^^^ `boards` is a `&` reference, so the data it refers to cannot be borrowed as mutable

For more information about this error, try `rustc --explain E0596`.

The actual problem here is a missing Clone implementation for Board. Its absence causes Rust to choose the Clone implementation on shared references, so the type of boards here is actually &Vec<Board>; this can be verified by adding an explicit type annotation to the let-bound boards.

The help is not helpful.

It would be much nicer if Rust could somehow point out the missing Clone implementation. Perhaps it should be suspicious of missing mutability and a uselessly cloned shared reference?

@jimblandy jimblandy added A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Dec 4, 2021
@Aaron1011
Copy link
Member

This is #83099 - the lint is currently turned off by default.

GuillaumeGomez added a commit to GuillaumeGomez/rust that referenced this issue Dec 4, 2023
Tweak `.clone()` suggestion to work in more cases

When going through auto-deref, the `<T as Clone>` impl sometimes needs to be specified for rustc to actually clone the value and not the reference.

```
error[E0507]: cannot move out of dereference of `S`
  --> $DIR/needs-clone-through-deref.rs:15:18
   |
LL |         for _ in self.clone().into_iter() {}
   |                  ^^^^^^^^^^^^ ----------- value moved due to this method call
   |                  |
   |                  move occurs because value has type `Vec<usize>`, which does not implement the `Copy` trait
   |
note: `into_iter` takes ownership of the receiver `self`, which moves value
  --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL
help: you can `clone` the value and consume it, but this might not be your desired behavior
   |
LL |         for _ in <Vec<usize> as Clone>::clone(&self.clone()).into_iter() {}
   |                  ++++++++++++++++++++++++++++++            +
```

When encountering a move error, look for implementations of `Clone` for the moved type. If there is one, check if all its obligations are met. If they are, we suggest cloning without caveats. If they aren't, we suggest cloning while mentioning the unmet obligations, potentially suggesting `#[derive(Clone)]` when appropriate.

```
error[E0507]: cannot move out of a shared reference
  --> $DIR/suggest-clone-when-some-obligation-is-unmet.rs:20:28
   |
LL |     let mut copy: Vec<U> = map.clone().into_values().collect();
   |                            ^^^^^^^^^^^ ------------- value moved due to this method call
   |                            |
   |                            move occurs because value has type `HashMap<T, U, Hash128_1>`, which does not implement the `Copy` trait
   |
note: `HashMap::<K, V, S>::into_values` takes ownership of the receiver `self`, which moves value
  --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL
help: you could `clone` the value and consume it, if the `Hash128_1: Clone` trait bound could be satisfied
   |
LL |     let mut copy: Vec<U> = <HashMap<T, U, Hash128_1> as Clone>::clone(&map.clone()).into_values().collect();
   |                            ++++++++++++++++++++++++++++++++++++++++++++           +
help: consider annotating `Hash128_1` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | pub struct Hash128_1;
   |
```

Fix rust-lang#109429.

When encountering multiple mutable borrows, suggest cloning and adding
derive annotations as needed.

```
error[E0596]: cannot borrow `sm.x` as mutable, as it is behind a `&` reference
  --> $DIR/accidentally-cloning-ref-borrow-error.rs:32:9
   |
LL |     foo(&mut sm.x);
   |         ^^^^^^^^^ `sm` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |
help: `Str` doesn't implement `Clone`, so this call clones the reference `&Str`
  --> $DIR/accidentally-cloning-ref-borrow-error.rs:31:21
   |
LL |     let mut sm = sr.clone();
   |                     ^^^^^^^
help: consider annotating `Str` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct Str {
   |
help: consider specifying this binding's type
   |
LL |     let mut sm: &mut Str = sr.clone();
   |               ++++++++++
```

Fix rust-lang#34629. Fix rust-lang#76643. Fix rust-lang#91532.
@bors bors closed this as completed in f67523d Dec 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants