]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/vectors.md
Auto merge of #24865 - bluss:range-size, r=alexcrichton
[rust.git] / src / doc / trpl / vectors.md
1 % Vectors
2
3 A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard
4 library type [`Vec<T>`][vec]. The `T` means that we can have vectors
5 of any type (see the chapter on [generics][generic] for more).
6 Vectors always allocate their data on the heap.
7 You can create them with the `vec!` macro:
8
9 ```rust
10 let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
11 ```
12
13 (Notice that unlike the `println!` macro we’ve used in the past, we use square
14 brackets `[]` with `vec!` macro. Rust allows you to use either in either situation,
15 this is just convention.)
16
17 There’s an alternate form of `vec!` for repeating an initial value:
18
19 ```
20 let v = vec![0; 10]; // ten zeroes
21 ```
22
23 ## Accessing elements
24
25 To get the value at a particular index in the vector, we use `[]`s:
26
27 ```rust
28 let v = vec![1, 2, 3, 4, 5];
29
30 println!("The third element of v is {}", v[2]);
31 ```
32
33 The indices count from `0`, so the third element is `v[2]`.
34
35 ## Iterating
36
37 Once you have a vector, you can iterate through its elements with `for`. There
38 are three versions:
39
40 ```rust
41 let mut v = vec![1, 2, 3, 4, 5];
42
43 for i in &v {
44     println!("A reference to {}", i);
45 }
46
47 for i in &mut v {
48     println!("A mutable reference to {}", i);
49 }
50
51 for i in v {
52     println!("Take ownership of the vector and its element {}", i);
53 }
54 ```
55
56 Vectors have many more useful methods, which you can read about in [their
57 API documentation][vec].
58
59 [vec]: ../std/vec/index.html
60 [generic]: generics.html