问题
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