Skip to content

Error message about immutable binding is not actually caused by a binding #49839

Open
@gdesmott

Description

@gdesmott

See the following code:

use std::collections::HashMap;

struct Test {
    v: u32,
}

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

    let values = map.values();
    for mut t in values {
        t.v += 1;
    }
}

It raises this compiler error:

error[E0594]: cannot assign to field t.v of immutable binding
--> /tmp/test.rs:14:9
|
14 | t.v += 1;
| ^^^^^^^^ cannot mutably borrow field of immutable binding

The fix is to use values_mut() instead of values().
But the error message is confusing as the problem here is not the binding as t itself is mut making it harder to debug for newcomers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.P-mediumMedium priorityT-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