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.")
}
}
// 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.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]
<details>
* `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<T>` 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: