有没有办法匹配两个枚举变量,并将匹配的变量绑定到变量?

Pau*_*rth 8 rust

我有这个枚举:

enum ImageType {
    Png,
    Jpeg,
    Tiff,
}
Run Code Online (Sandbox Code Playgroud)

有没有办法匹配前两个中的一个,并将匹配的值绑定到变量?例如:

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 => { ... },
}
Run Code Online (Sandbox Code Playgroud)

该语法不起作用,但有没有呢?

Sør*_*sen 9

看起来你问的是如何在第一种情况下绑定值.如果是这样,你可以使用这个:

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 => { ... }
}
Run Code Online (Sandbox Code Playgroud)

如果还想获取match语句之外的绑定值,可以使用以下命令:

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
    },
};
Run Code Online (Sandbox Code Playgroud)

在那种情况下,最好先简单一下let h = get_image_type(),然后match h(感谢BHustus).

请注意使用h @ <value>语法将变量名称绑定h到匹配的值().