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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题