douzhan8652 2018-12-02 17:50
浏览 35
已采纳

具有接口类型的通道和指向结构的指针作为具体类型

I'm attempting to generalize some of my code and I thought I might be able to pull some common code together, but I'm hitting my head against a type-system problem.

Let's assume I have an interface like this:

type Hashable interface {
    GetHash() []byte
}

and I have a couple of concrete types like this:

type Transaction struct {
    Hash                 []byte    `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
}

func (m *Transaction) GetHash() []byte {
    if m != nil {
        return m.Hash
    }
    return nil
}

Notice that these are generated by protoc, and I can probably not change them easily. While the type itself does not implement Hashable, the pointer to the struct should if I'm not mistaken.

The issue arises when I create a function that accepts a channel of type chan Hashable and try to pass in a chan *Transaction, like this:

func consume(c chan Hashable) {
    // Do something with the elements from c
}

func main() {
    var c2 chan *Transaction
    consume(c2)
}

(I created a small example to show this issue in the Playground)

I could of course create a new struct that repacks the fields that consume needs, but that seems like a much worse option.

Is there a clean solution for this?

  • 写回答

1条回答 默认 最新

  • duanbi1888 2018-12-02 22:27
    关注

    The problem is: chan *Transaction is not an interface - it's a specific type. So it cannot implement interface or chan Hashable by it's nature. You need to use specific channel.

    You can convert Transaction values to Hashable on the fly with a grouting like this:

    func convertor(ct chan *Transaction) chan Hashable {
        ch := make(chan Hashable)
        go func() {
            for t := range(ct) {
                ch <- Hashable(t)
            }
    
        }()
        return ch
    }
    

    and call

    consume(convertor(c2))
    

    https://play.golang.org/p/pd2EfhCehYz

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

报告相同问题?

悬赏问题

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