From 0694dfe205d1eae3d424a8b274daacbbddc6cbb9 Mon Sep 17 00:00:00 2001 From: sgoudham Date: Sat, 15 Jan 2022 01:24:17 +0000 Subject: [PATCH] Add hashmaps --- hashmap/Cargo.toml | 8 ++++++++ hashmap/src/main.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 hashmap/Cargo.toml create mode 100644 hashmap/src/main.rs diff --git a/hashmap/Cargo.toml b/hashmap/Cargo.toml new file mode 100644 index 0000000..bdd8dfc --- /dev/null +++ b/hashmap/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "hashmap" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/hashmap/src/main.rs b/hashmap/src/main.rs new file mode 100644 index 0000000..218362f --- /dev/null +++ b/hashmap/src/main.rs @@ -0,0 +1,42 @@ +use std::collections::HashMap; + +fn main() { + // Create & Insert Into New Hashmap + let mut scores = HashMap::new(); + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + + // Demonstrate Ownership + let field_name = String::from("Favorite color"); + let field_value = 2; + scores.insert(field_name, field_value); + // field_name and field_value are now owned by hashmap scores + + // Retrieve Value From Hashmap + let option = scores.get(String::from("Favourite color").as_str()); + + // Iterate Through Hashmap + for (key, value) in &scores { + println!("[{}] -> {}", key, value); + } + + // Overwrite a Value + scores.insert(String::from("Blue"), 20); + println!("{:?}", scores); + + // Only Insert A Value if Key Has No Value + let mut scores2 = HashMap::new(); + scores2.insert(String::from("Blue"), 10); + scores2.entry(String::from("Yellow")).or_insert(50); + scores2.entry(String::from("Blue")).or_insert(50); + println!("{:?}", scores2); + + // Update Value Based On Pre-existing value + let text = "hello world wonderful world"; + let mut map = HashMap::new(); + for word in text.split_whitespace() { + let count = map.entry(word).or_insert(0); + *count += 1; + } + println!("{:?}", map); +}