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 ifiis out of range.v.get(i)returns anOption<&T>:Some(&value)orNone. 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:
pub fn squares(n: u32) -> Vec<u32>: the squares of1throughnin order, built withVec::newandpush.squares(4)is[1, 4, 9, 16], andsquares(0)is empty.pub fn get_or_zero(v: &[i32], i: usize) -> i32: the element at indexi, or0if the index is out of range. Useget, not[].pub fn largest(v: &[i32]) -> Option<i32>: the biggest element, orNonefor an empty slice.