Skip to content

Bad suggestion when calling iter instead of iter_mut #82081

Closed
@estebank

Description

@estebank

Given:

use std::collections::HashMap;

struct Test {
    v: u32,
}

fn main() {
    let mut map = HashMap::new();
    map.insert("a", Test { v: 0 });

    for (k, mut v) in map.iter() {
        v.v += 1;
    }
}

we emit:

error[E0594]: cannot assign to `v.v` which is behind a `&` reference
  --> src/main.rs:12:9
   |
11 |     for (k, mut v) in map.iter() {
   |             ----- help: consider changing this to be a mutable reference: `&mut Test`
12 |         v.v += 1;
   |         ^^^^^^^^ `v` is a `&` reference, so the data it refers to cannot be written

but we should be instead suggesting

error[E0594]: cannot assign to `v.v` which is behind a `&` reference
  --> src/main.rs:12:9
   |
11 |     for (k, mut v) in map.iter() {
   |             -----         ---- help: consider calling `iter_mut` instead
   |             |
   |             this binding is of type `&Test`
12 |         v.v += 1;
   |         ^^^^^^^^ `v` is a `&` reference, so the data it refers to cannot be written

CC #49839

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-confusingDiagnostics: Confusing error or lint that should be reworked.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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