diff --git a/ch8/hash-maps/Cargo.lock b/ch8/hash-maps/Cargo.lock new file mode 100644 index 0000000..c2c1d27 --- /dev/null +++ b/ch8/hash-maps/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "hash-maps" +version = "0.1.0" diff --git a/ch8/hash-maps/Cargo.toml b/ch8/hash-maps/Cargo.toml new file mode 100644 index 0000000..32db93e --- /dev/null +++ b/ch8/hash-maps/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "hash-maps" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/ch8/hash-maps/src/main.rs b/ch8/hash-maps/src/main.rs new file mode 100644 index 0000000..86514f0 --- /dev/null +++ b/ch8/hash-maps/src/main.rs @@ -0,0 +1,66 @@ +use std::collections::HashMap; + +fn main() { + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + + let team_name = String::from("Blue"); + let score = scores.get(&team_name).copied().unwrap_or(0); + + for (key, value) in &scores { + println!("{key}: {value}"); + } + + // hash maps and ownership + // Copy trait implementers copy the values into the hash map. + // Owned values like String, values get moved + + let field_name = String::from("Favorite color"); + let field_value = String::from("Blue"); + + let mut map = HashMap::new(); + map.insert(field_name, field_value); + + // Below is invalid use after move + // println!("{field_name}"); + + // Updating a hash map + + // overwriting + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Blue"), 20); + + println!("{scores:?}"); + + // adding a key and value only if a key isn't present + let mut scores = HashMap::new(); + scores.insert(String::from("Blue"), 10); + + scores.entry(String::from("Yellow")).or_insert(50); + scores.entry(String::from("Blue")).or_insert(50); + + println!("{scores:?}"); + + // updating a value based on the old 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:?}"); + + // Custom hashing functions + // + // Why: Default one is secure but kinda slow + // Can use a different hashing function if too slow + // Talks about how in chapter 10. +} diff --git a/ch8/strings/src/main.rs b/ch8/strings/src/main.rs index e7f529d..21aed32 100644 --- a/ch8/strings/src/main.rs +++ b/ch8/strings/src/main.rs @@ -26,6 +26,8 @@ fn main() { let s_total = format!("{s1}-{s2}-{s3}"); - // stopped here: - // https://rust-book.cs.brown.edu/ch08-02-strings.html#internal-representation + // Rust doesn't allow indexing of Strings. + // UTF-8 characters can take over 2 bytes which makes it + // not nice for indexing. For rush, just use a vec of chars + // straight for the string list. }