Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to cast Structs for sending over a channel

Tags:

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")
}
like image 701
Matthew Campbell Avatar asked Nov 16 '12 22:11

Matthew Campbell


Video Answer


1 Answers

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:

    ....
    }
}
like image 160
jimt Avatar answered Sep 29 '22 02:09

jimt