2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RustでHashMapの値を更新したい

Posted at

###何したい?
HashMapのキーに対する値が入っていたら更新、入っていなかったら初期値を入れたい。

###やってみた
entryとor_insertを組み合わせる。

example
use std::collections::HashMap;

fn main() {
    let mut map:HashMap<String,i32> = HashMap::new();
    map.insert("a".to_string(), 1);

    *map.entry("a".to_string()).or_insert(0)  += 1;
    *map.entry("b".to_string()).or_insert(0)  += 1;

    println!("{:?}", map);
    println!("{:?}", map.get("b"));
    println!("{:?}", map.get("c"));
}
結果
{"a": 2, "b": 1}
Some(1)
None
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?