rust/src/doc/trpl/vectors.md

61 lines
1.4 KiB
Markdown
Raw Normal View History

2015-04-07 21:16:02 -05:00
% Vectors
2015-04-18 15:20:56 -05:00
A vector is a dynamic or growable array, implemented as the standard
2015-04-27 07:09:38 -05:00
library type [`Vec<T>`][vec]. The `T` means that we can have vectors
of any type (see the chapter on [generics][generic] for more).
Vectors always allocate their data on the heap.
2015-04-18 15:20:56 -05:00
You can create them with the `vec!` macro:
2015-04-07 21:16:02 -05:00
2015-04-18 15:20:56 -05:00
```rust
let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
```
2015-04-18 15:20:56 -05:00
(Notice that unlike the `println!` macro weve used in the past, we use square
brackets `[]` with `vec!` macro. Rust allows you to use either in either situation,
2015-04-07 21:16:02 -05:00
this is just convention.)
2015-04-18 15:20:56 -05:00
Theres an alternate form of `vec!` for repeating an initial value:
2015-04-07 21:16:02 -05:00
```rust
2015-04-07 21:16:02 -05:00
let v = vec![0; 10]; // ten zeroes
```
2015-04-18 15:20:56 -05:00
## Accessing elements
2015-04-07 21:16:02 -05:00
2015-04-18 15:20:56 -05:00
To get the value at a particular index in the vector, we use `[]`s:
2015-04-07 21:16:02 -05:00
2015-04-18 15:20:56 -05:00
```rust
let v = vec![1, 2, 3, 4, 5];
2015-04-07 21:16:02 -05:00
2015-04-18 15:20:56 -05:00
println!("The third element of v is {}", v[2]);
2015-04-07 21:16:02 -05:00
```
2015-04-18 15:20:56 -05:00
The indices count from `0`, so the third element is `v[2]`.
## Iterating
Once you have a vector, you can iterate through its elements with `for`. There
are three versions:
```rust
let mut v = vec![1, 2, 3, 4, 5];
for i in &v {
println!("A reference to {}", i);
}
for i in &mut v {
println!("A mutable reference to {}", i);
}
for i in v {
println!("Take ownership of the vector and its element {}", i);
}
```
Vectors have many more useful methods, which you can read about in [their
API documentation][vec].
[vec]: ../std/vec/index.html
[generic]: generics.html