Simple question about match

I have a problem with designing code flow around match. Let me explain by providing code example:

let val = match something
{
Ok(v)=>v,
Err(e)=>???? What do do here? I don't want to print anything, I want to react "somehow"
};

So, basically the situation is that in case of success, that is OK, sure, easy path, everything works and val gets the v value and the program can continue. But what value should get the val in case of Err? And how to check it later? By using if? I find that somewhat not clear how to solve that particular scenario.

Ultimately you have to decide what you want to happen if the operation fails, and type that inside the Err branch. For example, to crash the program on failure:

let val = match something {
    Ok(v) => v,
    Err(e) => {
        panic!("Crash the program!");
    }
};
// or
let val = something.unwrap();
// or with the error message
let val = something.expect("Crash the program!");

To select 17 as a default value:

let val = match something {
    Ok(v) => v,
    Err(e) => 17,
};
// or
let val = something.unwrap_or(17);

To return the error from the function immediately:

let val = match something {
    Ok(v) => v,
    Err(e) => return Err(e),
};
// or
let val = something?;
3 Likes

Like in any other programming language, it depends on what your function needs to do with val.

If you cannot continue if something is an Err, then you would probably return in the Err branch, and you can maybe shorten the whole thing to let val = something?;.

If you want val to have a default value if something is an Err, then you would construct a new default value (or whatever you need) in the Err branch. In this case you could maybe shorten the whole thing to let val = something.unwrap_or_default() (or unwrap_or or unwrap_or_else depending on what type val is, is expensive to construct, etc.)

If you have some other need for val if something is an Err, then you would need to provide some more context before I could make a suggestion.

Thanks for the examples. I appreciate it.

1 Like

A bigger example:

let val = match something {
    Ok(v) => v * 10,
    Err(e) => {
        let foo = func_one();
        let bar = func_two();
        foo + bar
    }
};