Vectors

Vectors are re-sizable arrays. Like slices, their size is not known at compile
time, but they can grow or shrink at any time. A vector is represented using
3 words: a pointer to the data, its length, and its capacity. The capacity
indicates how much memory is reserved for the vector. The vector can grow as
long as the length is smaller than the capacity. When this threshold needs to
be surpassed, the vector is reallocated with a larger capacity.

  1. fn main() {
  2. // Iterators can be collected into vectors
  3. let collected_iterator: Vec<i32> = (0..10).collect();
  4. println!("Collected (0..10) into: {:?}", collected_iterator);
  5. // The `vec!` macro can be used to initialize a vector
  6. let mut xs = vec![1i32, 2, 3];
  7. println!("Initial vector: {:?}", xs);
  8. // Insert new element at the end of the vector
  9. println!("Push 4 into the vector");
  10. xs.push(4);
  11. println!("Vector: {:?}", xs);
  12. // Error! Immutable vectors can't grow
  13. collected_iterator.push(0);
  14. // FIXME ^ Comment out this line
  15. // The `len` method yields the current size of the vector
  16. println!("Vector size: {}", xs.len());
  17. // Indexing is done using the square brackets (indexing starts at 0)
  18. println!("Second element: {}", xs[1]);
  19. // `pop` removes the last element from the vector and returns it
  20. println!("Pop last element: {:?}", xs.pop());
  21. // Out of bounds indexing yields a panic
  22. println!("Fourth element: {}", xs[3]);
  23. // FIXME ^ Comment out this line
  24. // `Vector`s can be easily iterated over
  25. println!("Contents of xs:");
  26. for x in xs.iter() {
  27. println!("> {}", x);
  28. }
  29. // A `Vector` can also be iterated over while the iteration
  30. // count is enumerated in a separate variable (`i`)
  31. for (i, x) in xs.iter().enumerate() {
  32. println!("In position {} we have value {}", i, x);
  33. }
  34. // Thanks to `iter_mut`, mutable `Vector`s can also be iterated
  35. // over in a way that allows modifying each value
  36. for x in xs.iter_mut() {
  37. *x *= 3;
  38. }
  39. println!("Updated vector: {:?}", xs);
  40. }

More Vec methods can be found under the
std::vec module