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