From f9f04651ce8cee6cd6da9073daaf35253b394862 Mon Sep 17 00:00:00 2001 From: gendx Date: Thu, 9 Feb 2023 21:45:43 +0000 Subject: [PATCH] Add more example methods to Vec and HashMap. (#373) --- src/std/hashmap.md | 14 ++++++++++++++ src/std/vec.md | 15 +++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/std/hashmap.md b/src/std/hashmap.md index 2ff029b0..5d6c16e3 100644 --- a/src/std/hashmap.md +++ b/src/std/hashmap.md @@ -22,5 +22,19 @@ fn main() { None => println!("{book} is unknown.") } } + + // Use the .entry() method to insert a value if nothing is found. + for book in ["Pride and Prejudice", "Alice's Adventure in Wonderland"] { + let page_count: &mut i32 = page_counts.entry(book.to_string()).or_insert(0); + *page_count += 1; + } + + println!("{page_counts:#?}"); } ``` + +
+ +* Unlike `vec!`, there is unfortunately no standard `hashmap!` macro. + +
diff --git a/src/std/vec.md b/src/std/vec.md index d9ef89df..fc3a5aee 100644 --- a/src/std/vec.md +++ b/src/std/vec.md @@ -12,6 +12,17 @@ fn main() { v2.extend(v1.iter()); v2.push(9999); println!("v2: len = {}, capacity = {}", v2.len(), v2.capacity()); + + // Canonical macro to initialize a vector with elements. + let mut v3 = vec![0, 0, 1, 2, 3, 4]; + + // Retain only the even elements. + v3.retain(|x| x % 2 == 0); + println!("{v3:?}"); + + // Remove consecutive duplicates. + v3.dedup(); + println!("{v3:?}"); } ``` @@ -22,14 +33,14 @@ methods on a `Vec`. [2]: https://doc.rust-lang.org/std/vec/struct.Vec.html#deref-methods-[T]
- + * `Vec` is a type of collection, along with `String` and `HashMap`. The data it contains is stored on the heap. This means the amount of data doesn't need to be known at compile time. It can grow or shrink at runtime. * Notice how `Vec` is a generic type too, but you don't have to specify `T` explicitly. As always with Rust type inference, the `T` was established during the first `push` call. * `vec![...]` is a canonical macro to use instead of `Vec::new()` and it supports adding initial - elements to the vector. + elements to the vector. * To index the vector you use `[` `]`, but they will panic if out of bounds. Alternatively, using `get` will return an `Option`. The `pop` function will remove the last element. * Show iterating over a vector and mutating the value: