Rust Fundamentals · 15 XP Pro

Vectors

A Vec<T> is a growable list of values of one type, stored on the heap. Arrays have a fixed size; vectors can grow and shrink.

let mut v: Vec<i32> = Vec::new();
v.push(10);
v.push(20);
let w = vec![1, 2, 3];      // macro for a vector with initial values
println!("{}", v.len());    // 2

There are two ways to read an element:

  • v[i] returns the element but panics if i is out of range.
  • v.get(i) returns an Option<&T>: Some(&value) or None. Use it when the index might be bad.
let third = w[2];                 // 3
let missing = w.get(10);          // None
let copy: i32 = *w.get(0).unwrap_or(&0);

Note the & and *: get hands out a reference to the element, so you dereference it with * to get a plain i32 copy.

A function that only reads a list should take a slice, &[i32]. Passing &v where v is a Vec<i32> works automatically.

Your task

Everything must be pub. Write:

  1. pub fn squares(n: u32) -> Vec<u32>: the squares of 1 through n in order, built with Vec::new and push. squares(4) is [1, 4, 9, 16], and squares(0) is empty.
  2. pub fn get_or_zero(v: &[i32], i: usize) -> i32: the element at index i, or 0 if the index is out of range. Use get, not [].
  3. pub fn largest(v: &[i32]) -> Option<i32>: the biggest element, or None for an empty slice.

Next lesson →

Sign in to run your code. It's free.