In Rust, a HashMap works like a dictionary — it stores key-value pairs where each key maps to a value. Bring it into scope with use std::collections::HashMap;.
use std::collections::HashMap;
let mut scores: HashMap<&str, i32> = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
scores.insert("Charlie", 72);
The type parameters <&str, i32> specify the key type and value type. You can also initialize using HashMap::from:
use std::collections::HashMap;
let ages: HashMap<&str, i32> = HashMap::from([
("Alice", 25),
("Bob", 30),
]);
println!("{}", ages["Alice"]); // 25
println!("{}", ages.len()); // 2
Assignment
Follow the Coding Tutorial and create a HashMap named scores with three student scores!
Hint
Declare let mut scores: HashMap<&str, i32> = HashMap::new(); then use scores.insert("Alice", 95) to add entries.
Free plan: 30 tutor messages. Premium is unlimited.