CodeBlanks Logo Icon CodeBlanks

Entry API

Insert into a map safely with the Entry API.

The Entry API

For "insert if missing, update if present", entry is used. It does a single lookup and gives a mutable reference to the value:

let metin = "elma armut elma kiraz elma armut";
let mut sayim = HashMap::new();
for k in metin.split_whitespace() {
    *sayim.entry(k).or_insert(0) += 1;
}

or_insert(0) puts 0 if the key is missing and returns &mut V in every case; it's dereferenced with * and incremented.

Other entry methods

or_default() puts the type's default; and_modify changes only an existing value:

let mut gruplar: HashMap<char, Vec<&str>> = HashMap::new();
for k in ["elma", "erik", "ayva"] {
    gruplar.entry(k.chars().next().unwrap()).or_default().push(k);
}

let mut puan = HashMap::new();
puan.entry("ali").and_modify(|p| *p += 10).or_insert(50);   // 50 if missing, +10 if present

Practice Word count

Count the words in "elma armut elma kiraz elma armut" with entry(..).or_insert(0). Collect the result into a Vec, sort it and print it with {:?}.

Starter code

main.rs
use std::collections::HashMap;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::collections::HashMap;

fn main() {
    let metin = "elma armut elma kiraz elma armut";
    let mut sayim = HashMap::new();
    for k in metin.split_whitespace() {
        *sayim.entry(k).or_insert(0) += 1;
    }
    let mut v: Vec<(&str, i32)> = sayim.into_iter().collect();
    v.sort();
    println!("{:?}", v);
}

Expected output

[("armut", 2), ("elma", 3), ("kiraz", 1)]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between <code>or_insert_with(Vec::new)</code> and <code>or_insert(Vec::new())</code>?

  • or_insert errors
  • or_insert_with sorts
  • or_insert_with produces the value only if the key is missing Correct answer
  • No difference

Explanation: The argument of or_insert is always computed; for expensive defaults prefer or_insert_with or or_default.

2 Initialize if missing

Question
*sayim.entry(k).____(0) += 1;
Answer
*sayim.entry(k).or_insert(0) += 1;

Explanation: or_insert puts the value if missing and returns &mut V.

3 Method and behaviour

Term Meaning
or_insert(v) Put v if missing
or_insert_with(f) Call f() if missing
or_default() Default if missing
and_modify(f) Change if present

All lessons in Intermediate