How to Use HashMap in Rust

The Complete Guide

Create a HashMap in Rust using std::collections::HashMap, insert key-value pairs with insert, and retrieve values using get.

Use std::collections::HashMap to store key-value pairs where keys are unique and values can be retrieved by key. Create a mutable map, insert entries with insert, and retrieve values with get.

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    let team_name = String::from("Blue");
    let score = scores.get(&team_name).copied().unwrap_or(0);
    println!("{score}");
}