Rust Tutorial: HashMap in Rust
Store and look up key-value pairs with std::collections::HashMap.
Concepts in this chapter
You will learn and practice:
- **HashMap** — insert, get, get with default (entry, or_insert)
- **Iteration** — for (k, v) in &map
- **entry API** — map.entry(key).or_insert(value)
- **use std::collections::HashMap**
---
Basics
```rust
use std::collections::HashMap;
let mut ages = HashMap::new();
ages.insert("Alice", 30);
ages.insert("Bob", 25);
println!("{}", ages.get("Alice").unwrap());
```
---
entry and or_insert
```rust
ages.entry("Charlie").or_insert(0);
let count = ages.entry("Diana").or_insert(0);
*count += 1;
```
---
What's Next?
Next: **Functions** — defining and calling functions.
What you'll learn in this Rust hashmap in rust tutorial
This interactive Rust tutorial has 2 hands-on exercises. Estimated time: 12 minutes.
- insert and get — Create a HashMap with &str keys and i32 values. Insert "Alice" -> 30 and "Bob" -> 25. Print the value for "Alice" (use .…
- contains_key and entry — Given a map with "go" -> 2009 and "python" -> 1991, check if "go" exists and print "found" or "not found". Then use .ent…
Rust HashMap in Rust concepts covered
- Concepts in this chapter
- Basics
- entry and or_insert
- What's Next?