Skip to content

Wrong syntax suggested by "consider changing this to be a mutable reference" with mut parameter in closure when iterating a vector #115259

Closed
@chylex

Description

@chylex

Code

fn main() {}

pub trait Layer {
	fn process(&mut self) -> u32;
}

pub struct State {
	layers: Vec<Box<dyn Layer>>,
}

impl State {
	pub fn process(&mut self) -> u32 {
		self.layers.iter().fold(0, |result, mut layer| result + layer.process())
	}
}

Current output

error[E0596]: cannot borrow `**layer` as mutable, as it is behind a `&` reference
  --> src/main.rs:13:59
   |
13 |         self.layers.iter().fold(0, |result, mut layer| result + layer.process())
   |                                                                 ^^^^^^^^^^^^^^^ `layer` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |
help: consider changing this to be a mutable reference
   |
13 |         self.layers.iter().fold(0, |result, mut lmut ayer| result + layer.process())
   |                                                  +++

Desired output

No response

Rationale and extra context

Initially, my State.process function looked like this:

self.layers.iter().fold(0, |result, layer| result + layer.process())

This led to a diagnostic that already has an open issue #62387 (it should suggest iter -> iter_mut).

I didn't notice I was not using iter_mut and tried changing layer -> mut layer, which led to the compiler somehow adding a second mut in the middle of the closure parameter.

obrazek

I don't know what the desired output should be in this case; I don't think mut parameter is correct here either way, but it might be worth investigating why the compiler is making a syntactically wrong suggestion.

Other cases

No response

Anything else?

Tested on 1.71.0 and 1.72.0 (stable-x86_64-unknown-linux-gnu).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions