1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-01-07 08:45:24 +02:00

Update vec.md (#240)

Adding Speaker Notes about type inference in collections and `vec![]` macro.
This commit is contained in:
Igor Petruk 2023-01-23 18:04:52 +00:00 committed by GitHub
parent 49c9ba692e
commit 30291800ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,9 +4,6 @@
```rust,editable
fn main() {
let mut numbers = Vec::new();
numbers.push(42);
let mut v1 = Vec::new();
v1.push(42);
println!("v1: len = {}, capacity = {}", v1.len(), v1.capacity());
@ -15,6 +12,9 @@ fn main() {
v2.extend(v1.iter());
v2.push(9999);
println!("v2: len = {}, capacity = {}", v2.len(), v2.capacity());
let mut numbers = vec![1, 2, 3];
numbers.push(42);
}
```
@ -23,3 +23,13 @@ methods on a `Vec`.
[1]: https://doc.rust-lang.org/std/vec/struct.Vec.html
[2]: https://doc.rust-lang.org/std/vec/struct.Vec.html#deref-methods-[T]
<details>
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.
</details>