How can I update a value in a mutable HashMap?

后端 未结 3 1335
我寻月下人不归
我寻月下人不归 2020-11-28 10:46

Here is what I am trying to do:

use std::collections::HashMap;

fn main() {
    let mut my_map = HashMap::new();
    my_map.insert(\"a\", 1);
    my_map.inse         


        
3条回答
  •  广开言路
    2020-11-28 11:30

    Indexing immutably and indexing mutably are provided by two different traits: Index and IndexMut, respectively.

    Currently, HashMap does not implement IndexMut, while Vec does.

    The commit that removed HashMap's IndexMut implementation states:

    This commit removes the IndexMut impls on HashMap and BTreeMap, in order to future-proof the API against the eventual inclusion of an IndexSet trait.

    It's my understanding that a hypothetical IndexSet trait would allow you to assign brand-new values to a HashMap, and not just read or mutate existing entries:

    let mut map = HashMap::new();
    map["key"] = "value";
    

    For now, you can use get_mut:

    *my_map.get_mut("a").unwrap() += 10;
    

    Or the entry API:

    *my_map.entry("a").or_insert(42) += 10;
    

提交回复
热议问题