创建一个通用的通道

huangapple go评论93阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年10月15日 01:51:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/69575259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定