RRust By Example
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

HashMap stores key-value pairs.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples