猿问

如何定义动态接口/结构

我是 Go 的新手,真的在寻找一些指导。


在我的应用程序中,我有一个接收事件的通道,我想要一个像这样的界面:


{

  "type": "event1",

  "data": {}

}

其中的结构data取决于type.


然后在通道中侦听这些事件的代码将根据事件的类型知道期望什么样的结构。


我怎样才能定义这样的接口?这在 Go 中被认为是一种好的做法吗?


提前致谢


皈依舞
浏览 94回答 1
1回答

幕布斯6054654

您正在寻找一个type switch:package mainimport (&nbsp; &nbsp; "fmt")type X struct {&nbsp; &nbsp; i int}func main() {&nbsp; &nbsp; c := make(chan interface{}, 5)&nbsp; &nbsp; c <- 4&nbsp; &nbsp; c <- "hi"&nbsp; &nbsp; c <- X{}&nbsp; &nbsp; close(c)&nbsp; &nbsp; for value := range c {&nbsp; &nbsp; &nbsp; &nbsp; switch v := value.(type) {&nbsp; &nbsp; &nbsp; &nbsp; case int:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("got int", v)&nbsp; &nbsp; &nbsp; &nbsp; case string:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("got string", v)&nbsp; &nbsp; &nbsp; &nbsp; case X:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("got X", v)&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("unexpected type %T\n", value)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答