Error Handling with Result in Rust

Understand how to handle errors gracefully in Rust by using the Result enum for functions that can return errors.

Error Handling with Result in Rust
Photo by Zan / Unsplash

Understand how to handle errors gracefully in Rust by using the Result enum for functions that can return errors.

fn divide(a: f64, b: f64) -> Result<f64, &'static str> {
    if b == 0.0 {
        Err("Division by zero is not allowed")
    } else {
        Ok(a / b)
    }
}

fn main() {
    let result = divide(10.0, 2.0);
    match result {
        Ok(value) => println!("Result: {}", value),
        Err(err) => println!("Error: {}", err),
    }
}