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

diagnostics: suggest iter_mut() where trying to modify .iter()'ed vector elements inplace #62387

Closed
matthiaskrgr opened this issue Jul 4, 2019 · 3 comments · Fixed by #115308
Assignees
Labels
A-diagnostics Area: Messages for errors, warnings, and lints C-enhancement Category: An issue proposing an enhancement or a PR with one. D-newcomer-roadblock Diagnostics: Confusing error or lint; hard to understand for new users. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@matthiaskrgr
Copy link
Member

code:

#[derive(Debug)]
struct A {
    a: i32,
}

impl A {
    fn double(&mut self) {
        self.a += self.a
    }
}

fn main() {
    let mut v = [A { a: 4 }];
    v.iter().for_each(|a| a.double());
    println!("{:?}", v);
}

The code gives the following not-very-helpful warning:

error[E0596]: cannot borrow `*a` as mutable, as it is behind a `&` reference
  --> src/main.rs:14:27
   |
14 |     v.iter().for_each(|a| a.double());
   |                        -  ^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |                        |
   |                        help: consider changing this to be a mutable reference: `&mut A`

warning: variable does not need to be mutable
  --> src/main.rs:13:9
   |
13 |     let mut v = [A { a: 4 }];
   |         ----^
   |         |
   |         help: remove this `mut`
   |
   = note: #[warn(unused_mut)] on by default

error: aborting due to previous error

trying to use

v.iter().for_each(|&mut a| a.double());

and a none-mutable vector just causes more errors

error[E0308]: mismatched types
  --> src/main.rs:14:24
   |
14 |     v.iter().for_each(|&mut a| a.double());
   |                        ^^^^^^ types differ in mutability
   |
   = note: expected type `&A`
              found type `&mut _`
   = help: did you mean `mut a: &&A`?

The actual fix is to use iter_mut() instead of just iter():

#[derive(Debug)]
struct A {
    a: i32,
}

impl A {
    fn double(&mut self) {
        self.a += self.a
    }
}

fn main() {
    let mut v = [A { a: 4 }];
    v.iter_mut().for_each(|a| a.double());
    println!("{:?}", v);
}

It would be very helpful the compiler could suggest iter_mut()!

@matthiaskrgr
Copy link
Member Author

matthiaskrgr commented Jul 4, 2019

@rustbot modify labels: A-diagnostics

@rustbot
Copy link
Collaborator

rustbot commented Jul 4, 2019

Error: Parsing label command in comment failed: ...ify labels|error: must have : or to as label starter at >| A-diagnos...

Please let @rust-lang/release know if you're having trouble with this bot.

@rustbot rustbot added the A-diagnostics Area: Messages for errors, warnings, and lints label Jul 4, 2019
@crlf0710 crlf0710 added C-enhancement Category: An issue proposing an enhancement or a PR with one. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jun 11, 2020
@matthiaskrgr
Copy link
Member Author

Urgh I just ran into this AGAIN. 😭

My code was something like this:

use std::path::PathBuf;

struct Container {
    things: Vec<PathBuf>,
}

impl Container {
    fn things(&mut self) -> &[PathBuf] {
        &self.things
    }
}

// contains containers
struct ContainerContainer {
    contained: Vec<Container>
}

impl ContainerContainer {
    fn contained(&self ) -> &[Container] {
        &self.contained
    }

    fn all_the_things(&mut self) -> &[PathBuf]
    {
       let a = &self.contained().iter().flat_map(|container| container.things()).cloned().collect::<Vec<PathBuf>>();
        unimplemented!();
    }
}

pub fn main() {}

The error shown:

error[E0596]: cannot borrow `*container` as mutable, as it is behind a `&` reference
  --> src/main.rs:25:62
   |
25 |        let a = &self.contained().iter().flat_map(|container| container.things()).cloned().collect::<Vec<PathBuf>>();
   |                                                   ---------  ^^^^^^^^^ `container` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |                                                   |
   |                                                   help: consider changing this to be a mutable reference: `&mut Container`

error: aborting due to previous error; 1 warning emitted

So I changed it to |&mut container| and was greeted with

error[E0308]: mismatched types
  --> src/main.rs:25:51
   |
25 |        let a = &self.contained().iter().flat_map(|&mut container| container.things()).cloned().collect::<Vec<PathBuf>>();
   |                                                   ^^^^^----------
   |                                                   |    |
   |                                                   |    expected due to this
   |                                                   types differ in mutability
   |                                                   help: did you mean `container`: `&&Container`
   |
   = note:      expected reference `&Container`
           found mutable reference `&mut _`

which made me wonder if I was better off with the origin |container|.

I really wish rust could somehow detect the .iter().bla(|x| fn_that_requires_mut(x) pattern and suggest to use iter_mut() :(

@estebank estebank added the D-newcomer-roadblock Diagnostics: Confusing error or lint; hard to understand for new users. label Aug 3, 2023
@chenyukang chenyukang self-assigned this Aug 27, 2023
Dylan-DPC added a commit to Dylan-DPC/rust that referenced this issue Sep 11, 2023
…ut, r=davidtwco

suggest iter_mut() where trying to modify elements from .iter()

Fixes rust-lang#115259
Fixes rust-lang#62387
@bors bors closed this as completed in 68c2f5b Sep 11, 2023
github-actions bot pushed a commit to rust-lang/miri that referenced this issue Sep 12, 2023
…twco

suggest iter_mut() where trying to modify elements from .iter()

Fixes rust-lang/rust#115259
Fixes rust-lang/rust#62387
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 C-enhancement Category: An issue proposing an enhancement or a PR with one. D-newcomer-roadblock Diagnostics: Confusing error or lint; hard to understand for new users. 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.

5 participants