Skip to content

cannot assign to data in an index of HashMap<_, _> diagnostic suggests solution that does not type check #134917

@epilys

Description

@epilys

Code

use std::collections::HashMap;

fn main() {
    let mut map: HashMap<bool, bool> = HashMap::default();
    map[&true] = false;
}

Current output

error[E0594]: cannot assign to data in an index of `HashMap<bool, bool>`
 --> src/main.rs:5:5
  |
5 |     map[&true] = false;
  |     ^^^^^^^^^^^^^^^^^^ cannot assign
  |
  = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap<bool, bool>`
help: to modify a `HashMap<bool, bool>`, use `.get_mut()`, `.insert()` or the entry API
  |
5 |     map.insert(&true, false);
  |        ~~~~~~~~     ~      +
5 |     map.get_mut(&true).map(|val| { *val = false; });
  |        ~~~~~~~~~     ~~~~~~~~~~~~~~~~~~        ++++
5 |     let val = map.entry(&true).or_insert(false);
  |     +++++++++    ~~~~~~~     ~~~~~~~~~~~~     +

For more information about this error, try `rustc --explain E0594`.

Desired output

error[E0594]: cannot assign to data in an index of `HashMap<bool, bool>`
 --> src/main.rs:5:5
  |
5 |     map[&true] = false;
  |     ^^^^^^^^^^^^^^^^^^ cannot assign
  |
  = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap<bool, bool>`
help: to modify a `HashMap<bool, bool>`, use `.get_mut()`, `.insert()` or the entry API
  |
5 |     map.insert(true, false);
  |        ~~~~~~~~    ~      +
5 |     map.get_mut(&true).map(|val| { *val = false; });
  |        ~~~~~~~~~     ~~~~~~~~~~~~~~~~~~        ++++
5 |     let val = map.entry(true).or_insert(false);
  |     +++++++++    ~~~~~~~    ~~~~~~~~~~~~     +

For more information about this error, try `rustc --explain E0594`.

Rationale and extra context

HashMap::insert and HashMap::entry take owned key values.

Other cases

Rust Version

$ rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-unknown-linux-gnu
release: 1.83.0
LLVM version: 19.1.1

Anything else?

Similar fixes might be necessary for other container types in std::collections

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions