21

In GOLANG is there an easy to way to cast structs for polymorphic behavior across channels? I'm trying to send different versions of a struct across one channel, so for example I'm going to have different types of Events, like a LoginEvent. Each one will have different amounts of data in the struct.

package main

import "fmt"


type Event struct {
    EvtType EvtType
    Username string
    Data string
}


type LoginEvent struct {
    Event
    CallBackChannel  chan *Event
}


type EvtType int

const (
    Login EvtType = iota+1
    Logout
    ChatMessage
    Presense
    BuddyList
)


func main() {
    fakeOutputChan := make(chan<- *Event)

        ourSrvChannel := make(chan *Event)
        lg := (LoginEvent{Event{Login,"",""} ,ourSrvChannel})
    fakeOutputChan <- (*Event)(&lg)

    fmt.Println("Hello, playground")
}
Matthew Campbell
  • 401
  • 1
  • 4
  • 7

1 Answers1

25

The idiomatic way to do is, is to use interfaces and then do a type assertion on the receiving end. Your Event struct should ideally be an interface.

type Event interface {
    // Methods defining data all events share.
}

type UserEvent struct {
    Name string
}

// Define methods on *UserEvent to have it qualify as Event interface.

type LoginEvent struct {
    ...
}

// Define methods on *LoginEvent to have it qualify as Event interface.

Then you can define your channel to accept anything that qualifies as the Event interface.

ch := make(chan Event)

The receiving end will receive the Event objects and can do a type assertion to see what concrete type underlies it:

select {
case evt := <- ch:
    if evt == nil {
        return
    }

    switch evt.(type) {
    case *LoginEvent:

    case *UserEvent:

    ....
    }
}
jimt
  • 21,810
  • 7
  • 63
  • 57