capypad
0 Tage Serie
rust / beginner
Snippet

HashMap: Schlüssel-Wert-Speicherung

HashMap<K, V> speichert Schlüssel-Wert-Paare mit O(1) durchschnittlicher Lookup-Zeit. Verwende die entry API für effiziente Behandlung fehlender Schlüssel. Die get-Methode gibt Option<&V> zurück und zwingt dich, fehlende Schlüssel zu behandeln. HashMap erfordert, dass K den Eq und Hash Trait implementiert.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use std::collections::HashMap;
 
fn main() {
// Creating an empty HashMap
let mut scores: HashMap<&str, i32> = HashMap::new();
// Inserting key-value pairs
scores.insert("Alice", 100);
scores.insert("Bob", 85);
scores.insert("Charlie", 92);
// Using get with Option handling
match scores.get("Alice") {
Some(score) => println!("Alice's score: {}", score),
None => println!("Alice not found"),
}
// Using entry API for conditional insertion
let entry = scores.entry("Diana").or_insert(0);
*entry += 10;
// Iterating over key-value pairs
for (name, score) in &scores {
println!("{}: {}", name, score);
}
// Updating a value based on existing one
let name = "Bob";
if let Some(score) = scores.get_mut(name) {
*score += 5;
}
println!("Bob's updated score: {}", scores[name]);
}
Erklärung
1
use std::collections::HashMap;
Importiert HashMap aus dem Standard-Bibliothek collections-Modul
2
let mut scores: HashMap<&str, i32> = HashMap::new();
Erstellt eine leere HashMap mit &str Schlüsseln und i32 Werten
3
scores.insert("Alice", 100);
Fügt ein Schlüssel-Wert-Paar in die HashMap ein
4
scores.entry("Diana").or_insert(0);
Entry API: fügt 0 ein wenn Schlüssel nicht existiert, gibt veränderliche Referenz auf existierenden oder neuen Wert zurück
5
for (name, score) in &scores
Iteration über Referenzen zu Schlüssel-Wert-Paaren ohne die HashMap zu konsumieren