Multiple match on different types


#1

Hi How can you do a multiple match which different types

Ie

I have an enum like

pub enum ElementStreamFormat {
  TimeFloatMessage(DataUniqueIdentifier, DateTime<UTC>, Vec<(String, f64)>),
  TimeStringMessage(DataUniqueIdentifier, DateTime<UTC>, Vec<(String, String)>),
}

If I do a multiple match like

match val {
    ElementStreamFormat::TimeStringMessage(ref id, ref datetime, ref message) | 
    ElementStreamFormat::TimeFloatMessage(ref id, ref datetime, ref message)  => {
        // do something ie convert the float to string
    }
}

I get errors like

ElementStreamFormat::TimeFloatMessage(ref id, ref datetime, ref message) => { 
    |                                                                                     ^^^^^^^^^^^ expected struct `std::string::String`, found f64
    |
    = note: expected type `&std::vec::Vec<(std::string::String, std::string::String)>`
               found type `&std::vec::Vec<(std::string::String, f64)>`

How can I specify the types in the match ?

Thanks


#2

Use two separate match arms, or don’t capture message.

You can’t use | here, because for this to work all variables you capture must have same types. message can’t be sometimes from TimeFloatMessage, sometimes from TimeStringMessage, because they’re not the same type.


#3

Ah Ok. I will refactor my match arm into a function as is 20 or so lines.

Thanks