Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to match two enum variants and also bind the matched variant to a variable?

Tags:

rust

I have this enum:

enum ImageType {
    Png,
    Jpeg,
    Tiff,
}

Is there any way to match one of the first two, and also bind the matched value to a variable? For example:

match get_image_type() {
    Some(h: ImageType::Png) | Some(h: ImageType::Jpeg) => {
        // Lots of shared code
        // that does something with `h`
    },
    Some(ImageType::Tiff) => { ... },
    None => { ... },
}

That syntax doesn't work, but is there any that does?

like image 290
Paul A Jungwirth Avatar asked Mar 16 '18 21:03

Paul A Jungwirth


1 Answers

It looks like you are asking how to bind the value inside the first case. If so, you can use this:

match get_image_type() {
    // use @ to bind a name to the value
    Some(h @ ImageType::Png) | Some(h @ ImageType::Jpeg) => {
        // Lots of shared code that does something with `h`
    },
    Some(ImageType::Tiff) => { ... },
    None => { ... }
}

If you want to also get the bound value outside of the match statement, you can use the following:

let matched = match get_image_type() {
    Some(h @ ImageType::Png) | Some(h @ ImageType::Jpeg) => {
        // Lots of shared code that does something with `h`
        Some(h)
    },
    Some(h @ ImageType::Tiff) => {
        // ...
        Some(h)
    },
    None => {
        // ...
        None
    },
};

In that case, though, it might be better to simply let h = get_image_type() first, and then match h (thanks to BHustus).

Note the use of the h @ <value> syntax to bind the variable name h to the matched value (source).

like image 114
Søren Mortensen Avatar answered Oct 21 '22 13:10

Søren Mortensen