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

流过昼夜 提交于 2020-01-11 08:18:13

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/49329586/is-there-a-way-to-match-two-enum-variants-and-also-bind-the-matched-variant-to-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!