英文:
Create a generic channel
问题
我有一个定义了Subscribers
映射通道的结构体。
package ws
type SessionHandler struct {
Subscribers map[chan interface{}]bool
}
我想要使其能够使用任何类型的通道进行实例化,就像这样:
type WsSession struct {
handler *ws.SessionHandler
}
handler := &ws.SessionHandler{
Subscribers: make(map[chan WsResponse]bool),
}
我提供的代码示例无法工作(cannot use make(map[chan WsResponse]bool) (value of type map[chan WsResponse]bool) as map[chan interface{}]bool value in struct literal
),但是我该如何更新它以适应我的需求呢?
英文:
I have my struct defining a Subscribers
that map channels.
package ws
type SessionHandler struct {
Subscribers map[chan interface{}]bool
}
I wanna make it possible to instantiate it with any kind of channel, like this:
type WsSession struct {
handler *ws.SessionHandler
}
handler := &ws.SessionHandler{
Subscribers: make(map[chan WsResponse]bool),
}
The code example I provided doesn't work (cannot use make(map[chan WsResponse]bool) (value of type map[chan WsResponse]bool) as map[chan interface{}]bool value in struct literal
), but how could I update it to my purposes?
答案1
得分: 0
我试图实现的目标将在Go v1.18中成为可能,正如@torek在我的问题中所评论的。
目前,我所做的是这样的:
handler := &ws.SessionHandler{
Subscribers: make(map[chan json.RawMessage]bool),
}
我不再依赖于go结构体,并在我的通道中传递json.RawMessage
。这不是完全干净的,因为我需要对我的消息进行编组/解组以进行适当的处理,但它是“通用的”,我可以实现我想要的功能。
英文:
What I was trying to accomplish will be possible in Go v1.18, as commented by @torek in my question.
For now, what I ended doing was this:
handler := &ws.SessionHandler{
Subscribers: make(map[chan json.RawMessage]bool),
}
I stopped relying on a go struct and communicated json.RawMessage
in my channels. It's not totally clean because I need to marshal/unmarshal my message to give the proper treatment, but its "generic" and I could accomplish what I was trying to do.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论