xxxxxxxxxx
fn main() {
let res = give_an_ok_result(false);
// Method 1: use match
match res {
Ok(r) => {
println!("Result succeeded");
assert_eq!(r, 10);
},
Err(e) => {
println!("Result errored!"); // This will run, given res will be an Err
assert_eq!(e, false);
}
}
// Method 2: use if
if let Err(e) = res {
println!("Error: {}", e); // "Error: false"
}
// You can also use `if let Ok(x) = res` to handle the Ok outcome
// Method 3: use expect
res.expect("You asked res to be an Err");
// This causes the program to panic and due to that, it is not good practice to use expect
// Method 4: Use unwrap_or
assert_eq!(res.unwrap_or(3i32), 3i32);
// This returns the Ok value in an Ok outcome, or the specified default for an Err outcome
// The 1st argument has to be the same type as the type of Ok of the Result
// There's other ways to handle results, these are only some.
}
fn give_an_ok_result(give_some: bool) -> Result<i32, bool> {
match give_some {
true => return Ok(10),
false => return Err(false)
}
}