Rust Unwrap and Expect

h‮//:sptt‬www.theitroad.com

In Rust, the unwrap and expect methods are used to extract the value from a Result if it is Ok, and panic if it is Err.

The unwrap method returns the value if it is Ok, or panics with a default error message if it is Err. Here's an example:

fn divide(x: i32, y: i32) -> Result<i32, &'static str> {
    if y == 0 {
        Err("division by zero")
    } else {
        Ok(x / y)
    }
}

fn main() {
    let result = divide(10, 2).unwrap();
    println!("Result: {}", result);
}

In this example, we're defining a function called divide that takes two integers and returns a Result containing the result of the division operation, or an error message if the second integer is zero.

In the main function, we're calling the divide function with the arguments 10 and 2, and then using the unwrap method to extract the result value from the Result. Since the division operation is successful in this case, the unwrap method returns the result value, which is then printed to the console.

If the Result had been an Err value, the unwrap method would have panicked with a default error message.

The expect method is similar to the unwrap method, but allows you to specify a custom error message to be printed if the Result is an Err. Here's an example:

fn main() {
    let result = divide(10, 0).expect("division by zero");
    println!("Result: {}", result);
}

In this example, we're calling the divide function with the arguments 10 and 0, which will result in an Err value being returned. We're then using the expect method to extract the result value from the Result and specify a custom error message to be printed if the Result is an Err. Since the Result is indeed an Err, the expect method panics with the specified error message.

While the unwrap and expect methods can be useful for simplifying error handling in some cases, it's important to use them judiciously and make sure that the potential for errors is properly handled in your code.