有没有办法匹配两个枚举变体并将匹配的变体绑定到变量? [英] Is there a way to match two enum variants and also bind the matched variant to a variable?
问题描述
我有这个枚举:
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?
推荐答案
您似乎在问如何绑定第一个案例中的值.如果是这样,你可以使用这个:
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 => { ... }
}
如果您还想在 match
语句之外获取绑定值,可以使用以下内容:
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
},
};
不过,在这种情况下,最好先简单地let h = get_image_type()
,然后match h
(感谢BHustus).
In that case, though, it might be better to simply let h = get_image_type()
first, and then match h
(thanks to BHustus).
注意使用 h @
语法将变量名称 h
绑定到匹配的值(来源).
Note the use of the h @ <value>
syntax to bind the variable name h
to the matched value (source).
这篇关于有没有办法匹配两个枚举变体并将匹配的变体绑定到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!