-
-
Save csknk/68b3d87bc76ce8c3431145fc0cc2fd3d to your computer and use it in GitHub Desktop.
unwrap_or_else examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//! Examples for `unwrap_or_else()` | |
use std::process; | |
fn func(in_num: u8) -> Option<&'static str> { | |
if in_num % 2 != 0 { | |
return None; | |
} | |
Some("even") | |
} | |
fn func_result(in_num: u8) -> Result<&'static str, &'static str> { | |
if in_num % 2 != 0 { | |
return Err("Can't do this because input is odd..."); | |
} | |
Ok("A good solid return...") | |
} | |
fn main() -> Result<(), &'static str> { | |
// Deal with a function that returns an Option | |
let a = func(3) | |
.unwrap_or_else(|| { "default" }); | |
let b = func(2) | |
.unwrap_or_else(|| { "default" }); | |
println!("a = {}, b = {}", a, b); | |
// Deal with a function that returns a Result | |
let c = func_result(3) | |
.unwrap_or_else(|e| { | |
println!("Error: {}", e); | |
// Let's assume that an Err from func_result should end programme. | |
process::exit(1); | |
// You could return a default here...e.g. `return "default";` | |
// It is expected that this closure returns the same type that it | |
// received. | |
}); | |
let d = func_result(2) | |
.unwrap_or_else(|e| { | |
println!("Error: {}", e); | |
// Let's assume that an Err from func_result should end programme. | |
process::exit(1); | |
// return "default"; | |
}); | |
println!("c = {}, d = {}", c, d); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment