Unwrapping Results in Rust
Unwrapping Results
89
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