HashMap and Ownership

HashMap is a collection that stores key-value pairs.

Creating a HashMap

use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Red"), 50);

Accessing Values

let team_name = String::from("Blue");
let score = scores.get(&team_name);

Ownership in HashMap

Values inserted into a HashMap are moved, not copied.

Iterating Over a HashMap

for (key, value) in &scores {
    println!("{}: {}", key, value);
}
← PrevNext →