From 7fdb9249afe07c75ad8bea568195a3a8d979d73a Mon Sep 17 00:00:00 2001 From: garhve Date: Fri, 30 Dec 2022 13:47:02 +0800 Subject: finish chapter 8 --- .../chapter-8-common-collections/hash/src/main.rs | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 rust/theBook/chapter-8-common-collections/hash/src/main.rs (limited to 'rust/theBook/chapter-8-common-collections/hash/src') diff --git a/rust/theBook/chapter-8-common-collections/hash/src/main.rs b/rust/theBook/chapter-8-common-collections/hash/src/main.rs new file mode 100644 index 0000000..d1e9a4c --- /dev/null +++ b/rust/theBook/chapter-8-common-collections/hash/src/main.rs @@ -0,0 +1,30 @@ +use std::collections::HashMap as hm; + +fn main() { + let mut scores = hm::new(); + + scores.insert(String::from("yellow"),10); + scores.insert(String::from("blue"),50); + + let tm = String::from("blue"); + + let score = scores.get(&tm).copied().unwrap_or(0); + + println!("{score}"); + + count_word(); +} + + +fn count_word() { + let text = "hello world wonderful world"; + + let mut hp = hm::new(); + + for word in text.split_whitespace() { + let count = hp.entry(word).or_insert(0); // or_insert return reference + *count += 1; + } + + println!("{:#?}", hp); +} -- cgit v1.2.3-70-g09d2