Logo

Developer learning path

Rust

Unwrapping Results in Rust

Unwrapping Results

89

#description

In Rust, when a function returns a value that may or may not be successful, it typically returns a Result type. The Result type is an enum, which has two possible values: Ok and Err. The Ok value contains the successful result of the operation, while the Err value holds an error message or an error object that indicates why the operation failed.

When working with Result types, we may want to "unwrap" the result to access the actual value contained in the Ok variant. This is typically done using the unwrap() method, which returns the contained value if the Result is Ok, or it panics and crashes the program if the Result is Err. This is why unwrapping Result values without proper error handling can be dangerous.

Here is an example:

                    
fn divide(dividend: i32, divisor: i32) -> Result<i32, &'static str> {
    if divisor == 0 {
        Err("divisor cannot be zero")
    } else {
        Ok(dividend / divisor)
    }
}

fn main() {
    let result = divide(10, 2);
    let quotient = result.unwrap();

    println!("The quotient is: {}", quotient);
}
                  

In the code above, the divide() function returns a Result<i32, &'static str> type. In the main() function, we call divide() with arguments 10 and 2, which should return Ok(5) as the dividend is divided by the divisor. We then use unwrap() to get the value contained in the Ok variant and assign it to the variable quotient. Finally, we print the quotient.

Note that if we had called divide() with values 10 and 0, the function would have returned Err("divisor cannot be zero") and trying to unwrap() the Result would have caused the program to panic. Therefore, it is important to handle errors appropriately when dealing with Result types.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.