Skip to content

rust suggests using IndexMut for maps, even though they don't implement the trait #143732

Open
@m4rch3n1ng

Description

@m4rch3n1ng

Code

use std::collections::BTreeMap;

fn main() {
    let mut map = BTreeMap::new();
    map.insert(0, "string".to_owned());

    let string = &map[&0];
    string.push_str("test");
}

Current output

error[E0596]: cannot borrow `*string` as mutable, as it is behind a `&` reference
 --> src/main.rs:8:5
  |
8 |     string.push_str("test");
  |     ^^^^^^ `string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
  |
help: consider changing this to be a mutable reference
  |
7 |     let string = &mut map[&0];
  |                   +++

For more information about this error, try `rustc --explain E0596`.
error: could not compile `tmp` (bin "tmp") due to 1 previous error

Desired output

error[E0596]: cannot borrow `*string` as mutable, as it is behind a `&` reference
 --> src/main.rs:8:5
  |
8 |     string.push_str("test");
  |     ^^^^^^ `string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
  |
help: consider changing this to be a mutable reference
  |
7 -     let string = &map[&0];
7 +     let string = map.get_mut(&0).unwrap();

For more information about this error, try `rustc --explain E0596`.
error: could not compile `tmp` (bin "tmp") due to 1 previous error

Rationale and extra context

trying to apply the suggestion gives the following error:

error[E0596]: cannot borrow data in an index of `std::collections::BTreeMap<i32, std::string::String>` as mutable
 --> src/main.rs:7:18
  |
7 |     let string = &mut map[&0];
  |                  ^^^^^^^^^^^^ cannot borrow as mutable
  |
  = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::collections::BTreeMap<i32, std::string::String>`
  = help: to modify a `std::collections::BTreeMap<i32, std::string::String>`, use `.get_mut()`, `.insert()` or the entry API

For more information about this error, try `rustc --explain E0596`.
error: could not compile `tmp` (bin "tmp") due to 1 previous error

the map types in the std (HashMap and BTreeMap) don't implement the IndexMut trait (sadly), but rustc still suggests trying to &mut map[index] (i.e. using IndexMut), even though it doesn't work.

Other cases

Rust Version

rustc 1.90.0-nightly (e43d139a8 2025-07-09)
binary: rustc
commit-hash: e43d139a82620a268d3828a73e12a8679339e8f8
commit-date: 2025-07-09
host: x86_64-unknown-linux-gnu
release: 1.90.0-nightly
LLVM version: 20.1.7

Anything else?

No response

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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions