drus39136 2014-08-31 15:19
浏览 50
已采纳

Golang:我可以投射到chan界面{}

I am trying to write a general purpose wrapper for subscriptions, something like:

type Subscriber interface{
    Subscribe(addr string) chan interface{}
}

Suppose there is a library I want to use which has a subscribe method in it, but which uses a chan library.Object. I would like to be able to do something like:

func (s *mySubscriber) Subscribe(addr string) chan interface{}{
    ch := make(chan library.Object)
    library.Subscribe(addr, ch)
    return chan interface{}(ch)
}

Currently, I don't believe such a cast is possible. And I don't want to modify the underlying library, since the wrapper should be agnostic to library implementations.

I've seen Is there a way to cast Structs for sending over a channel, but in that case the application can be modified to suit the need. Here, it can't. Is this possible? Is there a better way?

One solution is to pass in a general purpose channel into Subscribe, and to wait indefinetely on chan library.Object and fire anything that comes through on my general channel, but I didn't particularly like having to introduce another channel just to get around the type cast.

  • 写回答

2条回答 默认 最新

  • 普通网友 2014-08-31 18:19
    关注

    No, you can't do this with just a cast. You have to use an extra channel, as you have already considered. Fortunately, there is a helper library for this already (disclaimer: I wrote it). You want the Wrap function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序