![](https://i0.wp.com/media.dev.to/cdn-cgi/image/width=1000,height=500,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyct70ieqxepmj88jpdvf.png?w=1200&ssl=1)
The unwrap_or_else method is used as an Option or Result type.
Let’s see an example for both.
unwrap_or_else on an Option
For Option, the unwrap_or_else method is used to provide a fallback value if the Option is None**
fn main() { let some_value: Option<i32> = Some(10); let none_value: Option<i32> = None; // Using unwrap_or_else on an Option let result_some = some_value.unwrap_or_else(|| { println!("some_value was None, using default value."); 0 // Default value }); let result_none = none_value.unwrap_or_else(|| { println!("none_value was None, using default value."); 0 // Default value }); println!("Result when Option is Some: {}", result_some); println!("Result when Option is None: {}", result_none);
}
Output:
none_value was None, using default value.
Result when Option is Some: 10
Result when Option is None: 0
Explanation:
In this example, we have two Option variables, some_value and none_value. The some_value is Some(10) and the none_value is None.
The unwrap_or_else method is used on both Option variables. The closure passed to unwrap_or_else is only called when the Option is None. In this case, the closure prints a message and returns a default value of 0.
unwrap_or_else on a Result
For Result, the unwrap_or_else method is used to provide a fallback value if the Result is an Err.
fn main() { let ok_result: Result<i32, &str> = Ok(10); let err_result: Result<i32, &str> = Err("An error occurred"); // Using unwrap_or_else on a Result let result_ok = ok_result.unwrap_or_else(|err| { println!("ok_result was Err: {}, using default value.", err); 0 // Default value }); let result_err = err_result.unwrap_or_else(|err| { println!("err_result was Err: {}, using default value.", err); 0 // Default value }); println!("Result when Result is Ok: {}", result_ok); println!("Result when Result is Err: {}", result_err);
}
Output:
Error: Error message
Result when Result is Ok: 10
Result when Result is Err: 0
Explanation:
In this example, we have two Result variables, ok_result and err_result. The ok_result is Ok(10) and the err_result is Err(“An error occurred”).
The unwrap_or_else method is used on both Result variables. The closure passed to unwrap_or_else is only called when the Result is Err. In this case, the closure prints a message and returns a default value of 0.
Conclusion
In both examples, the unwrap_or_else method is used to provide a default value when the Option or Result is None or Err respectively.
The unwrap_or_else method takes a closure that returns the default value. The closure is only called when the Option is None or the Result is Err.
If you find this interesting and you want to get started with Rust, you can check this FREE playlist on YouTube: