douhuang2218 2013-12-13 01:30
浏览 46
已采纳

在Go中扩展接口

Fairly new to go. I'm trying to modify this go scribe server implementation:

https://github.com/samuel/go-thrift/blob/master/examples/scribe_server/main.go

I'd like to pass a channel to the Log() func so I can pass scribe data to a separate go routine but I'm not sure how to modify scribe/thrift.go to extend the log interface to be

Log(messages []*scribe.LogEntry, counts chan string)  

(or whether this is even needed and if there is some way to extend the interface without messing with the original library).

  • 写回答

1条回答 默认 最新

  • duangu1878 2013-12-13 01:43
    关注

    You can't modify or extend an already declared interface, you can only create a new one, possibly extending the old one. But you cannot re-declare methods in the interface.

    This means that what you want to do (modify the Scribe interface so that its Log method has a different signature) is not possible.

    What you can do is to have a type which holds your channel and embeds the structure you want to extend.

    Example:

    type Scribe interface {
        Log(Messages []*LogEntry) (ResultCode, error)
    }
    
    type ModifiedScribe struct {
        Scribe
        counts chan string
    }
    
    func (m *ModifiedScribe) Log(Messages []*LogEntry) (ResultCode, error) {
        // do something with m.counts
    
        // call embedded implementation's Log message
        return m.Scribe.Log(Messages)
    }
    

    The example above defines a struct which embeds a Scribe and defines its own Log method, utilizing the one of the embedded Scribe. This struct can be used wherever a Scribe is expected (as it implements the Scribe interface) but holds your additional channel.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看