Anunaki
Anunaki

Reputation: 881

rust: How to simplify enum nested match?

I got the result for std::result::Result<Row, sqlx::Error>, I want to check the row is found. the right code:

let sql = "select id,name from tablename LIMIT 0";
let r = sqlx::query_as::<_, Person>(sql).fetch_one(&pool).await;
if let Err(err) = r {
    match err {
        sqlx::Error::RowNotFound => println!("Not Found!!!"),
        _ => (),
    }
}

right way 1:

if let Err(err) = r {
    if let sqlx::Error::RowNotFound = err {
        println!("Not Found!!!");
    }
}

right way 2:

r.map_err(|err| if let sqlx::Error::RowNotFound = err {
    println!("Not Found!!!");
});

has the more simplify way?

Upvotes: 3

Views: 2758

Answers (1)

jschw
jschw

Reputation: 560

You can also match like this:

match r {
    Err(sqlx::Error::RowNotFound) => println!("Not Found!!!"),
    _ => (),
}

You could also look at match guards

Upvotes: 5

Related Questions