In Rust, the unwrap() method is a utility provided by the standard library that is commonly used with the Result and Option types to extract the value from the wrapped result or option, respectively.
For Result: The unwrap() method is used when you are sure that the Result is holding a valid value, and you want to extract that value while handling any potential errors in a simple and concise way. If the Result is an Ok variant, unwrap() will return the inner value (success case). However, if the Result is an Err variant, unwrap() will panic, causing the program to crash with an error message. Here’s an example of using unwrap() with Result:
fn divide(a: f64, b: f64) -> Result<f64, &'static str> {
if b == 0.0 {
return Err("Division by zero is not allowed.");
}
Ok(a / b)
}
fn main() {
let result = divide(10.0, 2.0).unwrap();
println!("Result: {}", result);
}