typestar

The entry API in Rust

One lookup instead of two: entry gives you the slot, occupied or not.

use std::collections::HashMap;

fn main() {
    let text = "the quick the lazy the end";
    let mut counts: HashMap<&str, u32> = HashMap::new();

    for word in text.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }

    let mut groups: HashMap<usize, Vec<&str>> = HashMap::new();
    for word in text.split_whitespace() {
        groups.entry(word.len()).or_insert_with(Vec::new).push(word);
    }

    println!("{}", counts["the"]);
    println!("{:?}", groups.get(&4));
}

How it works

  1. or_insert returns a mutable reference to the value.
  2. or_insert_with builds the default only when it is needed.
  3. *count += 1 writes through that reference.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
448
Tokens
147
Three-star pace
90 tpm

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

Type this snippet

Step 5 of 8 in Collections, step 34 of 39 in Language basics.

← Previous Next →