typestar

HashMap in Rust

The key-value map and its entry API.

use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<&str, i32> = HashMap::new();
    scores.insert("ada", 95);
    *scores.entry("ada").or_insert(0) += 5;

    let ada = scores.get("ada").copied().unwrap_or(0);
    let total: i32 = scores.values().sum();
    println!("{ada} {total} {}", scores.len());
}

How it works

  1. insert adds; entry().or_insert updates in place.
  2. get returns an Option for a missing key.
  3. values().sum() aggregates across the map.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
300
Tokens
109
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 1 of 2 in Maps & counting, step 12 of 14 in Iterators & closures.

← Previous Next →