liveBook · Manning

Key

As explained in Learn Rust in a Month of Lunches

A key is a value used to identify and look up an associated value in a map collection.

A key identifies a value in a map. Think of an address list: “email” can be the key, and an email address can be its value. In Rust, a HashMap stores these key–value pairs. Add one with .insert(key, value), then use the key to find its value. section 6.1.1

use std::collections::HashMap;
 
fn main() {
    let canadian_cities = vec!["Calgary", "Vancouver", "Gimli"];
    let german_cities = vec!["Karlsruhe", "Bad Doberan", "Bielefeld"];
 
    let mut city_hashmap = HashMap::new();
 
    for city in canadian_cities {
        city_hashmap.insert(city, "Canada");
    }
    for city in german_cities {
        city_hashmap.insert(city, "Germany");
    }
 
    println!("{:?}", city_hashmap["Bielefeld"]);
    println!("{:?}", city_hashmap.get("Bielefeld"));
    println!("{:?}", city_hashmap.get("Bielefeldd"));
}

Here, city names are keys and countries are values. The example inserts each pair, then looks up “Bielefeld” in two ways. section 6.1.1

Square-bracket lookup returns the value, but it panics if the key is missing. Use .get() when you are unsure: it returns Some(value) for an existing key and None for a missing one. In the city example, “Bielefeld” exists; “Bielefeldd” does not. section 6.1.1

A key also determines what happens when you add another pair. Inserting a value under an existing key replaces the old value. If you want to keep the existing value, .entry(key).or_insert(default) inserts the default only when the key is absent. That pattern can also initialize a count before you increase it. section 6.1.1

Do not rely on a HashMap’s keys appearing in a particular order when you loop over it. If you need keys in order, use a BTreeMap; its methods are similar for these examples. section 6.1.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains insertion, missing-key lookup, replacement, entry defaults, and ordering; does not develop map internals.
Examples
Shows city-to-country lookups, year-to-population pairs, repeated book keys, and book-title counts.
What it assumes
Introduces key–value pairs through an email-address analogy and relates square-bracket lookup to Vec indexing.
What you can do after
Apply it via Rust maps to choose keys, look up values safely, and handle existing entries.
How it connects
Connects keys to HashMap, BTreeMap, Option, Vec indexing, and the entry API.

Also explained in

Compare how 10 books explain key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.