rust/tests/ui/borrowck/issue-85765-closure.rs
Esteban Küber cc80106cb5 Provide more suggestions for cloning immutable bindings
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();
   |               ++++++++++
```

```
error[E0596]: cannot borrow `*inner` as mutable, as it is behind a `&` reference
  --> $DIR/issue-91206.rs:14:5
   |
LL |     inner.clear();
   |     ^^^^^ `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |
help: you can `clone` the `Vec<usize>` value and consume it, but this might not be your desired behavior
  --> $DIR/issue-91206.rs:11:17
   |
LL |     let inner = client.get_inner_ref();
   |                 ^^^^^^^^^^^^^^^^^^^^^^
help: consider specifying this binding's type
   |
LL |     let inner: &mut Vec<usize> = client.get_inner_ref();
   |              +++++++++++++++++
```
2023-12-04 21:54:34 +00:00

33 lines
1.4 KiB
Rust

fn main() {
let _ = || {
let mut test = Vec::new();
let rofl: &Vec<Vec<i32>> = &mut test;
//~^ HELP consider changing this binding's type
//~| HELP you can `clone` the `Vec<Vec<i32>>` value and consume it, but this might not be your desired behavior
rofl.push(Vec::new());
//~^ ERROR cannot borrow `*rofl` as mutable, as it is behind a `&` reference
//~| NOTE `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable
let mut mutvar = 42;
let r = &mutvar;
//~^ HELP consider changing this to be a mutable reference
*r = 0;
//~^ ERROR cannot assign to `*r`, which is behind a `&` reference
//~| NOTE `r` is a `&` reference, so the data it refers to cannot be written
#[rustfmt::skip]
let x: &usize = &mut{0};
//~^ HELP consider changing this binding's type
*x = 1;
//~^ ERROR cannot assign to `*x`, which is behind a `&` reference
//~| NOTE `x` is a `&` reference, so the data it refers to cannot be written
#[rustfmt::skip]
let y: &usize = &mut(0);
//~^ HELP consider changing this binding's type
*y = 1;
//~^ ERROR cannot assign to `*y`, which is behind a `&` reference
//~| NOTE `y` is a `&` reference, so the data it refers to cannot be written
};
}