Vecs Exercises

Overview

These exercises introduce Vec<T>, Rust’s growable, heap-allocated array type.


vecs1 - Creating Vectors

Concept: The vec! macro

fn array_and_vec() -> ([i32; 4], Vec<i32>) {
    let a = [10, 20, 30, 40];  // Array (fixed size)
 
    let v = vec![10, 20, 30, 40];  // Vector (growable)
 
    (a, v)
}

Key Takeaways:

  • vec! macro creates a new vector with initial values
  • Vectors are heap-allocated and can grow/shrink
  • Type annotation: Vec<T> where T is the element type
ArrayVector
[T; N]Vec<T>
Fixed sizeGrowable
Stack (usually)Heap

vecs2 - Iterating and Mapping

Concept: Multiple ways to transform vectors

Method 1: Loop with push

fn vec_loop(input: &[i32]) -> Vec<i32> {
    let mut output = Vec::new();
 
    for element in input {
        output.push(2 * element);
    }
 
    output
}

Method 2: Iterator with map (idiomatic!)

fn vec_map(input: &[i32]) -> Vec<i32> {
    input.iter().map(|element| 2 * element).collect()
}

Key Takeaways:

  • Vec::new() creates an empty vector
  • .push() adds elements to the end
  • .iter() creates an iterator over references
  • .map() transforms each element
  • .collect() gathers iterator results into a collection

💡 Performance tip: The .map().collect() approach is more efficient because it can preallocate capacity. Equivalent to using Vec::with_capacity(input.len()).


Iterator Chain Pattern

collection
    .iter()          // Create iterator
    .map(|x| ...)    // Transform each element
    .collect()       // Gather into Vec

This pattern is extremely common in Rust!


Rust Book Reference