Do two things in Result matching

Hi Rust community, I’m learning rust and would love to have a review of this tiny code snippets.

My original hint is to parse a string value to a int. If parsing fail I do something (here, I'm simply printing a message), and put a default value.

This technically works, but it looks weird to me:

let res = foo_str.parse::<u8>();

if res.is_err() {
    println!("Taking default value: 30");  // do something
}

let foo = match res {
    Ok(v) => v,
    Err(e) => 30,
};

They are a lot of example on Result handling over the internet with either print things or return thing but nothing explaining how to do something then return something.

Is there any rustonic way to handle this?

You can do it like this:

let foo: u8 = match foo_str.parse() {
    Ok(v) => v,
    Err(_) => {
        println!("Taking default value 30.");
        30
    }
};
1 Like

Hi, and thanks for the answer!

I tried something like this but failed getting confused by the lack of semicolon. It's definitely better.

Is this the usual way to do?

Well if you also want to print when picking the default, I'd go for the match. If you just wanted a default value and not print anything, I'd go for Result::unwrap_or.

let foo: u8 = foo_str.parse().unwrap_or(30);
1 Like