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 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题