capypad
0 Tage Serie
rust / beginner
Snippet

HashMap für Schlüssel-Wert-Speicherung

HashMap speichert Schlüssel-Wert-Paare mit O(1) durchschnittlicher Suchzeit. Verwende .get() um sicher Werte als Option<&V> abzurufen. Die .entry() API erlaubt das Einfügen nur wenn der Schlüssel nicht existiert mit or_insert().

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::collections::HashMap;
 
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
println!("Alice's score: {:?}", scores.get("Alice"));
scores.entry(String::from("Charlie")).or_insert(90);
for (name, score) in &scores {
println!("{}: {}", name, score);
}
}
Erklärung
1
use std::collections::HashMap;
HashMap muss von std::collections importiert werden
2
scores.insert(String::from("Alice"), 100);
Einfügen erfordert besessene String-Schlüssel, nicht &str-Literale
3
scores.get("Alice")
get() gibt Option<&V> zurück, None wenn Schlüssel fehlt
4
.entry(String::from("Charlie")).or_insert(90)
entry() gibt Entry-Enum zurück; or_insert setzt Standard wenn abwesend