0Pricing
Learn Rust Coding · Lesson

Entry API and Defaults

Update values ergonomically.

Why the Entry API?

Often you want to update a value if a key exists, or insert a default if it does not.

Doing this with get plus insert is clumsy. The entry API does it cleanly in one step.

entry Returns a Slot

Calling entry(key) gives you a handle to that key's place in the map.

From that handle you decide what to do: fill it with a default, or modify whatever is there.

use std::collections::HashMap;

fn main() {
    let mut m: HashMap<&str, i32> = HashMap::new();
    m.entry("a").or_insert(0);
    println!("{}", m["a"]);
}

All lessons in this course

  1. Building a HashMap
  2. Entry API and Defaults
  3. Working with HashSet
  4. Counting and Grouping
← Back to Learn Rust Coding