有没有办法将Structs转换为通过频道发送

Mat*_*ell 20 struct channel go

在GOLANG中,有一种简单的方法可以跨通道为多态行为转换结构吗?我试图在一个通道上发送不同版本的结构,所以例如我将有不同类型的事件,比如LoginEvent.每个结构中都有不同数量的数据.

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")
}
Run Code Online (Sandbox Code Playgroud)

jim*_*imt 24

惯用的方法是使用接口,然后在接收端进行类型断言.Event理想情况下,您的结构应该是一个接口.

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.
Run Code Online (Sandbox Code Playgroud)

然后,您可以定义您的频道以接受任何符合Event接口条件的频道.

ch := make(chan Event)
Run Code Online (Sandbox Code Playgroud)

接收端将接收Event对象并可以执行类型断言以查看其基础的具体类型:

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

    switch evt.(type) {
    case *LoginEvent:

    case *UserEvent:

    ....
    }
}
Run Code Online (Sandbox Code Playgroud)