Avoiding Unwrap

Note: No official YouTube video yet, but our Rust Developer Bootcamp covers this topic!

No video yet...

Exercises

Avoiding unwrap

// Modify `get_last` to handle all cases and make the program execute successfully.

fn get_last(nums: &mut Vec<i32>) -> i32 {
    nums.pop().unwrap()
}

fn main() {
    let mut vec1 = vec![1, 2, 3];
    let mut vec2 = vec![];
    assert!(matches!(get_last(&mut vec1), Ok(3)));
    assert!(matches!(get_last(&mut vec2), Err("Empty vector")));
}
Solution
fn get_last(nums: &mut Vec<i32>) -> Result<i32, &str> {
  if nums.len() == 0 {
      return Err("Empty vector");
  }
  Ok(nums.pop().unwrap())
}

fn main() {
  let mut vec1 = vec![1, 2, 3];
  let mut vec2 = vec![];
  assert!(matches!(get_last(&mut vec1), Ok(3)));
  assert!(matches!(get_last(&mut vec2), Err("Empty vector")));
}