H. Desane
H. Desane

Reputation: 653

How to refactor an if statement inside of a match arm?

I've got the following method:

fn get_error_id(err: CustomError) -> i64 {
    let default_id = 0;
    match err {
        CustomError::Unknown(response) => {
            if response.status == StatusCode::NOT_FOUND {
                404
            } else {
                default_id
            }
        }
        _ => default_id,
    }
}

Is there any way to refactor it to inline default_id?

Upvotes: 0

Views: 106

Answers (1)

apetranzilla
apetranzilla

Reputation: 5959

Match arms can include if expressions, so you can simplify the code like so:

fn get_error_id(err: CustomError) -> i64 {
    match err {
        CustomError::Unknown(ref r) if r.status == StatusCode::NOT_FOUND => 404,
        _ => 0, // default_id
    }
}

Upvotes: 3

Related Questions