Is there a way to match the two enumeration options, and also bind the selected option to a variable?

I have this listing:

enum ImageType { Png, Jpeg, Tiff, } 

Is there a way to map one of the first two, and also bind the mapped 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 => { ... }, } 

This syntax does not work, but is there something that does?

+7
rust
source share
1 answer

It looks like you are asking how to relate a value in 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 also want to get the bound value outside 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 this case, it might be better to just let h = get_image_type() and then match h (thanks to BHustus ).

Note the use of the h @ <value> syntax to bind the variable name h to a matching value ( source ).

+9
source share

All Articles