wiki/dev/lang/rust/hashmap.md
2024-01-09 13:18:39 +03:00

695 B

Hashmap.

Create / Use.

use std::collections::HashMap;

// Create.
let mut scores = HashMap::new();

// Insert.
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

// Get.
let team_name = String::from("Blue");
let score     = scores.get(&team_name).copied().unwrap_or(0); // .get() returns Option<&i32> hence the .copied().

// Iterate.
for (key, value) in &scores {
  println!("{key}: {value}");
}

// Update.
scores.insert(String::from("Blue"), 20);          // Overwrite.
scores.entry(String::from("Blue")).or_insert(20); // Only if not exists.
let count = scores.entry(String::from("Blue")).or_insert(0);
*count += 1; // Add, substract etc.