Rust Fundamentals · 15 XP Pro

Panic or Result?

Rust has two ways to say "something went wrong". A panic (panic!, an out-of-range index, or unwrap on None) stops the program: use it for bugs, situations that should be impossible.

For problems that can happen in normal use, such as bad input, return a Result<T, E>. It is an enum with two variants: Ok(value) for success and Err(error) for failure. The caller must decide what to do, usually with match.

fn halve(n: i32) -> Result<i32, String> {
    if n % 2 == 0 {
        Ok(n / 2)
    } else {
        Err(format!("{n} is odd"))
    }
}

match halve(7) {
    Ok(h) => println!("half is {h}"),
    Err(e) => println!("problem: {e}"),
}

Your task

Everything must be pub, because the tests use your crate as lesson.

  1. pub fn safe_divide(a: i32, b: i32) -> Result<i32, String> returns Ok(a / b), or Err("division by zero".to_string()) when b is 0.
  2. pub fn divide_or_zero(a: i32, b: i32) -> i32 calls safe_divide and uses match to return the quotient on success and 0 on failure.

Next lesson →

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