result exercises

This commit is contained in:
lilymonade 2025-03-11 18:03:50 +01:00
parent 4c9eef9b41
commit d045ac568e
Signed by: lilymonade
GPG Key ID: F8967EC454DBDCB6
2 changed files with 20 additions and 1 deletions

View File

@ -1 +1,2 @@
pub mod option;
pub mod result;

View File

@ -1,3 +1,4 @@
/// Returns `true` if the result contains an `Err`
pub fn is_err(res: &Result<i32, &str>) -> bool {
match res {
Err(_) => true,
@ -5,10 +6,12 @@ pub fn is_err(res: &Result<i32, &str>) -> bool {
}
}
/// Returns `true` if the result contains a `Ok`
pub fn is_ok(res: &Result<i32, &str>) -> bool {
!is_err(res)
}
/// Returns the wrapped `&str` if any, panic otherwise
pub fn get_err_or_panic(res: Result<i32, &str>) -> &str {
match res {
Err(e) => e,
@ -16,4 +19,19 @@ pub fn get_err_or_panic(res: Result<i32, &str>) -> &str {
}
}
pub fn
/// Returns the wrapped `i32` if any, panic otherwise
pub fn get_val_or_panic(res: Result<i32, &str>) -> i32 {
match res {
Ok(v) => v,
Err(_) => panic!("result was an error"),
}
}
/// Transforms `Ok` to `Some` and `Err` to `None`
/// effectively discarding the `Err` wrapped value
pub fn discard_err(res: Result<i32, &str>) -> Option<i32> {
match res {
Ok(v) => Some(v),
Err(_) => None,
}
}