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:
parent
3a734230c9
commit
f9f04651ce
@ -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>
|
||||||
|
@ -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:?}");
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user