]> git.proxmox.com Git - rustc.git/blame - src/doc/trpl/vectors.md
Imported Upstream version 1.5.0+dfsg1
[rustc.git] / src / doc / trpl / vectors.md
CommitLineData
9346a6ac
AL
1% Vectors
2
bd371182
AL
3A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard
4library type [`Vec<T>`][vec]. The `T` means that we can have vectors
5of any type (see the chapter on [generics][generic] for more).
6Vectors always allocate their data on the heap.
7You can create them with the `vec!` macro:
8
9```rust
10let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
9346a6ac
AL
11```
12
bd371182
AL
13(Notice that unlike the `println!` macro we’ve used in the past, we use square
14brackets `[]` with `vec!` macro. Rust allows you to use either in either situation,
9346a6ac
AL
15this is just convention.)
16
bd371182 17There’s an alternate form of `vec!` for repeating an initial value:
9346a6ac 18
62682a34 19```rust
9346a6ac
AL
20let v = vec![0; 10]; // ten zeroes
21```
22
bd371182
AL
23## Accessing elements
24
25To get the value at a particular index in the vector, we use `[]`s:
26
27```rust
28let v = vec![1, 2, 3, 4, 5];
29
30println!("The third element of v is {}", v[2]);
31```
32
33The indices count from `0`, so the third element is `v[2]`.
34
b039eaaf
SL
35It’s also important to note that you must index with the `usize` type:
36
37```ignore
38let v = vec![1, 2, 3, 4, 5];
39
40let i: usize = 0;
41let j: i32 = 0;
42
43// works
44v[i];
45
46// doesn’t
47v[j];
48```
49
50Indexing with a non-`usize` type gives an error that looks like this:
51
52```text
53error: the trait `core::ops::Index<i32>` is not implemented for the type
54`collections::vec::Vec<_>` [E0277]
55v[j];
56^~~~
57note: the type `collections::vec::Vec<_>` cannot be indexed by `i32`
58error: aborting due to previous error
59```
60
61There’s a lot of punctuation in that message, but the core of it makes sense:
62you cannot index with an `i32`.
63
bd371182
AL
64## Iterating
65
66Once you have a vector, you can iterate through its elements with `for`. There
67are three versions:
9346a6ac 68
bd371182
AL
69```rust
70let mut v = vec![1, 2, 3, 4, 5];
9346a6ac 71
bd371182
AL
72for i in &v {
73 println!("A reference to {}", i);
74}
9346a6ac 75
bd371182
AL
76for i in &mut v {
77 println!("A mutable reference to {}", i);
78}
79
80for i in v {
81 println!("Take ownership of the vector and its element {}", i);
82}
9346a6ac
AL
83```
84
bd371182
AL
85Vectors have many more useful methods, which you can read about in [their
86API documentation][vec].
87
88[vec]: ../std/vec/index.html
89[generic]: generics.html