From a8b3fed27dcb4a76333ac93aaa5f4143fe854ef8 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Mon, 23 Aug 2021 12:03:33 +0200 Subject: [PATCH] HashMap --- src/main.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/main.rs b/src/main.rs index 396d3f2..ff65a06 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,11 @@ mod word_utils; +use std::collections::HashMap; + use word_utils::{first_word, second_word}; fn main() { + // strings and functions let s = String::from("Hello world"); println!("first word: '{}'", first_word(&s)); println!("second word: '{}'", second_word(&s).unwrap()); @@ -15,6 +18,7 @@ fn main() { None => println!("match: second word of '{}' does not exist", s2), } + // vectors let v1 = vec![1, 2, 3]; println!("statically initialized vector: {:?}", v1); @@ -29,4 +33,35 @@ fn main() { for el in &v2 { println!("{}", el); } + + // hash maps + let mut scores = HashMap::new(); + scores.insert("john", 10); + scores.insert("mary", 20); + + println!("scores: {:?}", scores); + + // hash map with .collect() + let persons = vec![("homer", 42), ("marge", 30)]; + let collect_scores: HashMap<_, _> = persons.into_iter().collect(); + println!("collect_scores: {:?}", collect_scores); + + for (p, s) in &collect_scores { + println!("person {}: score {}", p, s); + } + + println!("john's score: {}", scores.get("john").unwrap()); + println!("jake's score: {}", scores.get("jake").unwrap_or(&-1)); + + // double scores + for (_, v) in scores.iter_mut() { + *v *= 2; + } + println!("scores after doubling: {:?}", scores); + + // double scores of immutable hashmap (rebuild it) + let collect_scores: HashMap<_, _> = collect_scores.iter() + .map(|(k, v)| (k, 2 * v)) + .collect(); + println!("collect_scores after rebuilding with doubling: {:?}", collect_scores); } -- 2.39.5