Search code examples
if-statementgological-or

Or inside condition


I have this code:

if ev, ok := evt.(*ATypeEvent); ok {
   //process ATypeEvent
} else if ev, ok := evt.(*BTypeEvent); ok {
   //process BTypeEvent
} else if ev, ok := evt.(*CTypeEvent); ok {
   //process CTypeEvent
}

It so now happens that I have 3 more event types, which all fit into one of the other 3 - I'd think I need a an OR.

But after several tries, I haven't been able to figure how to do it. This doesn't work:

if ev, ok := evt.(*ATypeEvent) || evt.(*XTypeEvent); ok {
   //process ATypeEvent and X
} else if ev, ok := evt.(*BTypeEvent)  || evt.(*YTypeEvent); ok {
   //process BTypeEvent and Y
} else if ev, ok := evt.(*CTypeEvent)  || evt.(*ZTypeEvent); ok {
   //process CTypeEvent and Z
}

nor something like

if ev, ok := evt.(*ATypeEvent) || ev, ok := evt.(*XTypeEvent); ok {

nor

if ev, ok := (evt.(*ATypeEvent) || evt.(*XTypeEvent ) ); ok {

How can this be done correctly?


Solution

  • Use a type switch as explained in Effective Go, a highly recommended resource for you to read and understand many things in Go:

    switch v := ev.(type) {
    case *ATypeEvent, *XTypeEvent:
        // process ATypeEvent and X
    case *BTypeEvent, *YTypeEvent:
        // process BTypeEvent and Y
    case *CTypeEvent, *ZTypeEvent:
        // process CTypeEvent and Z
    default:
        // should never happen
        log.Fatalf("error: unexpected type %T", v)
    }
    

    As for why your approach didn't work, Go's || and && operators require values of type bool and result in a single value of type bool, so assigning to ev, ok won't work as you wanted, nor will using a type assertion as a Boolean value. Without a type switch, you're stuck doing something like this:

    if ev, ok := evt.(*ATypeEvent); ok {
        //process ATypeEvent
    } else if ev, ok := evt.(*XTypeEvent); ok {
        //process XTypeEvent
    } else if ...