Early handling of unwanted cases

hi! i've been using rust for a bit, and encounterd the following pttern a few times. in a lot of languages, its common to use a negative validation for early return or handling. something that looks like this (in psudo code):

def foo(){
    if not (something) {return null}
    <the rest of the code>

and i have encounterd a few times where i would like to use the same pattern on an if let statment. a simple case would be:

if let Some(a) = foo {
    <rest of the code>
} else {return}

and i would want it to look more like:

if not let Some(a) = foo {
    return
}
<rest of the code>

obviously this case can be solved by using is_some() or something like that, but i want a general solution that works for more complicated generic types, for exapmle:

if let syn::Data::Struct(syn::DataStruct { fields, .. }) = &der.data {
    <rest of code>
} else {panic!()}

This is done with let-else, e.g.:

let Some(foo) = foo else {
    return;
}

If you want access to the value in the failure case, however, you need to fall back to let-match:

let bar = match foo {
    Ok(bar) => bar,
    Err(err) => panic!("{err}"),
};
5 Likes

thanks! the let-else was what i looked for!