1# Vectors 2 3Vectors are re-sizable arrays. Like slices, their size is not known at compile 4time, but they can grow or shrink at any time. A vector is represented using 53 parameters: 6- pointer to the data 7- length 8- capacity 9 10The capacity indicates how much memory is reserved for the vector. The vector 11can grow as long as the length is smaller than the capacity. When this threshold 12needs to be surpassed, the vector is reallocated with a larger capacity. 13 14```rust,editable,ignore,mdbook-runnable 15fn main() { 16 // Iterators can be collected into vectors 17 let collected_iterator: Vec<i32> = (0..10).collect(); 18 println!("Collected (0..10) into: {:?}", collected_iterator); 19 20 // The `vec!` macro can be used to initialize a vector 21 let mut xs = vec![1i32, 2, 3]; 22 println!("Initial vector: {:?}", xs); 23 24 // Insert new element at the end of the vector 25 println!("Push 4 into the vector"); 26 xs.push(4); 27 println!("Vector: {:?}", xs); 28 29 // Error! Immutable vectors can't grow 30 collected_iterator.push(0); 31 // FIXME ^ Comment out this line 32 33 // The `len` method yields the number of elements currently stored in a vector 34 println!("Vector length: {}", xs.len()); 35 36 // Indexing is done using the square brackets (indexing starts at 0) 37 println!("Second element: {}", xs[1]); 38 39 // `pop` removes the last element from the vector and returns it 40 println!("Pop last element: {:?}", xs.pop()); 41 42 // Out of bounds indexing yields a panic 43 println!("Fourth element: {}", xs[3]); 44 // FIXME ^ Comment out this line 45 46 // `Vector`s can be easily iterated over 47 println!("Contents of xs:"); 48 for x in xs.iter() { 49 println!("> {}", x); 50 } 51 52 // A `Vector` can also be iterated over while the iteration 53 // count is enumerated in a separate variable (`i`) 54 for (i, x) in xs.iter().enumerate() { 55 println!("In position {} we have value {}", i, x); 56 } 57 58 // Thanks to `iter_mut`, mutable `Vector`s can also be iterated 59 // over in a way that allows modifying each value 60 for x in xs.iter_mut() { 61 *x *= 3; 62 } 63 println!("Updated vector: {:?}", xs); 64} 65``` 66 67More `Vec` methods can be found under the 68[std::vec][vec] module 69 70[vec]: https://doc.rust-lang.org/std/vec/ 71