douhuan1648 2016-02-26 13:23
浏览 68
已采纳

Golang:通过空接口传递频道

I'm trying to do something that seems like it should be trivial until I read up and now it seems like it should be really complex. ;-) I've knocked up a test pattern to illustrate: http://play.golang.org/p/Re88vJZvPT

At the most basic I'm trying to have a function that can read data from a channel and spit it out on another one. Easy. The test does this as long as you use the pusher function shown. However the problem with this is that doing it this way I would need a different pusher function for each type of data I want to push through it. Now I've done similar things in the past with an empty interface as nothing in the pusher code cares about what's in the data structure. What I can't figure out is when I'm dealing with channels of an un-cared-about data structure.

To illustrate the concept of what I'm trying to achieve please see the function pusher_naive_generic.

However that doesn't work either so more reading up implied the way to do it was making use of reflection and finally you see my pusher_reflect_generic function(obviously this won't achieve the same intended function as the others it's showing where I got to before getting stuck). Which still fails because I can't get from an interface that contains a chan to the structure read from that chan.

Hopefully the code makes more sense of what I'm trying to achieve than my words actually do. I can make all of this work by explicitly coding for every type, but what I can't figure out how to do is code it for any future type.

  • 写回答

1条回答 默认 最新

  • du22399 2016-02-26 13:54
    关注

    If I have understood your question correctly, then this might be the solution:

    http://play.golang.org/p/xiDO7xkoW4

    func forwardChannel(i interface{}, o interface{}) {
    
        it, ot := reflect.TypeOf(i), reflect.TypeOf(o)
    
        if it != ot {
            panic("forwardChannel: both arguments must be of the same type")
        }
    
        iv, ov := reflect.ValueOf(i), reflect.ValueOf(o)
    
        for {
            v, k := iv.Recv()
            if !k {
                break
            }
            ov.Send(v)
        }
    
        ov.Close()
    
    }
    

    Note that Recv, Send and Close panic if i and o are not channels.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题