In Rust, you access values in a HashMap using square bracket notation or get():
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
let alice_score = scores["Alice"]; // 95
let bob_score = scores["Bob"]; // 87
Note: scores["key"] panics if the key doesn't exist. Use get() to get an Option instead, or contains_key() to check existence:
if scores.contains_key("Alice") {
println!("{}", scores["Alice"]);
}
Assignment
Follow the Coding Tutorial and access Alice's score from scores!
Hint
Use scores["Alice"] and assign it to alice_score.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check