繁体   English   中英

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

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

我有这个枚举:

enum ImageType {
    Png,
    Jpeg,
    Tiff,
}

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

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 => { ... },
}

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

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

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 => { ... }
}

如果还想获取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
    },
};

但是,在这种情况下,最好let h = get_image_type() ,然后match h (感谢BHustus )。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM