Google News
logo
Rust - Interview Questions
What is the difference between 'unwrap()' and 'expect()' in Rust?
In Rust, both `unwrap()` and `expect()` are methods provided by the `Option` and `Result` types to handle potential errors or `None` values. They allow you to extract the value from an `Option` or `Result` and return it, but they differ in their error handling behavior:

1. `unwrap()`:
   * `unwrap()` is a method available on `Option` and `Result` types that returns the inner value if it exists or panics if it encounters an `None` value (for `Option`) or an `Err` variant (for `Result`).
   * It is a shorthand for handling the common case where you expect the value to be present and you want the program to panic if it's not.
   * Using `unwrap()` is useful when you're confident that the value will always be present or when you want the program to terminate with an error message if the value is missing or an error occurs.

2. `expect()`:
   * `expect()` is similar to `unwrap()`, but it allows you to provide a custom error message as a parameter. Instead of a generic panic message, the error message passed to `expect()` is included in the panic message if an error occurs.
   * It provides more context and helps identify the source of the error when the program panics.
   * It is useful when you want to provide a specific error message to aid in debugging or understanding the reason for the panic.
Here's an example to illustrate the difference between `unwrap()` and `expect()`:
fn divide(a: f64, b: f64) -> f64 {
    if b == 0.0 {
        // Returns Err variant if division by zero occurs
        Err("Cannot divide by zero!")
    } else {
        // Returns Ok variant with the result of division
        Ok(a / b)
    }
}

fn main() {
    let result = divide(10.0, 0.0);

    // Using unwrap() - Program panics with a generic error message
    let value = result.unwrap();
    println!("Result: {}", value);

    // Using expect() - Program panics with a custom error message
    let value = result.expect("Division failed!");
    println!("Result: {}", value);
}​

In the example above, if the division by zero occurs, both `unwrap()` and `expect()` will panic. However, `unwrap()` will provide a generic panic message, while `expect()` allows you to provide a custom error message for more informative panic output.
Advertisement