Building a HashMap
Insert and look up by key.
What Is a HashMap?
A HashMap stores data as key-value pairs. You look things up by key instead of by index.
Think of a phone book: a name (key) maps to a number (value). HashMaps are perfect when you need fast lookups by a meaningful key.
Importing HashMap
Unlike Vec and String, HashMap is not in the prelude. You must bring it into scope.
Add a use line at the top of your file. This makes the name available throughout the module.
use std::collections::HashMap;
fn main() {
let scores: HashMap<String, i32> = HashMap::new();
println!("empty map len: {}", scores.len());
}All lessons in this course
- Building a HashMap
- Entry API and Defaults
- Working with HashSet
- Counting and Grouping