The opposite function of unwrap (Unwrap error)

Hello.
I am looking for a function that will be the opposite of the unwrap () function.
I would like to conveniently write unit tests.

  1. Is such a feature in the standard library?

  2. I made a function like this:

pub fn unwrap_err<T, E>(result: std::result::Result<T, E>) -> E {
    match result
    {
        Ok(_) => { panic!("should be error!"); },
        Err(e) => { return e; }
    };
}

Unwrap Error

  1. How do you convert it (unwrap_err) into a feature and add it to the structure?
// ???
pub trait UnwrapError<T, E> 
{
    fn unwrap_error(self, _: T, e: E) -> E 
    where Self: Sized 
    {
        let x = unwrap_err(self);
        return x;
    }
}
 
fn main()
{
    let x = ... ; // my struct
    let err = x.unwrap_error(); // panic if OK 
}
  • Result::unwrap_err() in the standard library

  • trait UnwrapError {
        type Error;
        
        fn unwrap_error (self: Self)
          -> Self::Error
        ;
    }
    
    impl<Ok, Err> UnwrapError for Result<Ok, Err> {
        type Error = Err;
        
        fn unwrap_error (self: Result<Ok, Err>)
          -> Err
        {
            match self {
                | Ok(_) => panic!("`.unwrap_error()`: unexpect `Ok` variant"),
                | Err(it) => it,
            }
        }
    }
    
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.