ErrorKind and pattern matching

Hello! Is there some way to find out the ErrorKind of a std::io::Error by pattern matching?

match res { // res is of the type std::result::Result<T, std::io::Error> 
   Err( /* what to put here */  ) => { /* do something for the Err of particular ErrorKind */ },
   _ => { /* do something for all the other cases including  the Ok variant*/  }
}

If this is not possible, then what is the best way to achieve the same?
Thanks :slight_smile:

Yes, the std::io::Error has a kind() function that will allow you to do exactly that.

You can use an if guard:

pub fn my_func() {
    let res = can_fail();
    
    match res {
        Err(err) if err.kind() == ErrorKind::WouldBlock => {
            // would block error
        },
        _ => {
            // other
        },
    }
}

playground

2 Likes

if guard is something new for me. Thanks.

If you are interested, there's a section in the Rust Reference about match guards.

If you know you've got an error you can also do a match directly on the kind().

pub fn my_func() {
    let res = can_fail();
    
    match res {
        Ok(_) => { /* other */ },
        Err(err) => {
            match err.kind() {
                ErrorKind::WouldBlock => { /* would block error */ },
                _ => { /* other */ },
            },
        },
    }
}

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.