1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-25 08:53:01 +02:00

Add more example methods to Vec and HashMap. (#373)

This commit is contained in:
gendx 2023-02-09 21:45:43 +00:00 committed by GitHub
parent 3a734230c9
commit f9f04651ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 2 deletions

View File

@ -22,5 +22,19 @@ fn main() {
None => println!("{book} is unknown.") 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:#?}");
} }
``` ```
<details>
* Unlike `vec!`, there is unfortunately no standard `hashmap!` macro.
</details>

View File

@ -12,6 +12,17 @@ fn main() {
v2.extend(v1.iter()); v2.extend(v1.iter());
v2.push(9999); v2.push(9999);
println!("v2: len = {}, capacity = {}", v2.len(), v2.capacity()); 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:?}");
} }
``` ```