Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 14, 2020 15:01
Show Gist options
  • Save rust-play/25b3d7c4e6d70d29159c8f3d4a0f2f51 to your computer and use it in GitHub Desktop.
Save rust-play/25b3d7c4e6d70d29159c8f3d4a0f2f51 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
//! 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