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:
9 let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
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.)
16 There’s an alternate form of `vec!` for repeating an initial value:
19 let v = vec![0; 10]; // ten zeroes
24 To get the value at a particular index in the vector, we use `[]`s:
27 let v = vec![1, 2, 3, 4, 5];
29 println!("The third element of v is {}", v[2]);
32 The indices count from `0`, so the third element is `v[2]`.
36 Once you have a vector, you can iterate through its elements with `for`. There
40 let mut v = vec![1, 2, 3, 4, 5];
43 println!("A reference to {}", i);
47 println!("A mutable reference to {}", i);
51 println!("Take ownership of the vector and its element {}", i);
55 Vectors have many more useful methods, which you can read about in [their
56 API documentation][vec].
58 [vec]: ../std/vec/index.html