Shorten complex match into if

Hi,

I'm currently a bit stuck as I don't know, how to shorten the following nested match.

match dotenv::from_path("config.env") {
    Err(e) => match e { 
        dotenv::Error::Io(ioerr) => match ioerr.kind() {
            std::io::ErrorKind::NotFound => {
                info!("config.env not found, creating example file");
                ()
            },
            _ => return Err("reading config.env failed".into()),
        },
        _ => return Err("reading config.env failed".into()),
    },
    _ => return Err("reading config.env failed".into()),
};

As you can see, I return 3 times the same error. I could have shorten this by using a flag, but instead I'd like to just handle this special error and all others should led to an error. So a simple if would be enough like this:

// Hint: this doesn't compile
let result = dotenv::from_path("config.env");
if result.err().Io().kind() == std::io::ErrorKind::NotFound {
    info!("config.env not found, creating example file");
} else {
    return Err("reading config.env failed".into());
}

Is it possible to just handle this special case and put all other cases in the same else-Branch?

Thank you

You can probably write it like:

match dotenv::from_path("config.env") {
    Err(dotenv::Error::Io(ioerr)) if ioerr.kind() == std::io::ErrorKind::NotFound => {
        info!("config.env not found, creating example file");
    },
    Err(_) => Err("reading config.env failed".into()),
    Ok(_) => {...},
}
1 Like

Thank you very much!

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.