beginnerCollections
HashMap Basic
Create and use hash maps for key-value storage.
HashMap Basic
Create and use hash maps for key-value storage.
Difficulty
Beginner
Code
rust
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert(String::from("Alice"), 10);
scores.insert(String::from("Bob"), 20);
scores.insert(String::from("Charlie"), 30);
for (name, score) in &scores {
println!("{}: {}", name, score);
}
let alice = scores.get("Alice");
println!("Alice: {:?}", alice);
}Explanation
This example demonstrates how to use hashmap basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the collections category to build a complete understanding of this topic.