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.
pub fn safe_divide(a: i32, b: i32) -> Result<i32, String>returnsOk(a / b), orErr("division by zero".to_string())whenbis0.pub fn divide_or_zero(a: i32, b: i32) -> i32callssafe_divideand usesmatchto return the quotient on success and0on failure.