在Go语言中扩展接口

huangapple go评论77阅读模式
英文:

Extending Interfaces in Go

问题

你好!以下是你要翻译的内容:

对于Go语言我还比较新手。我正在尝试修改这个Go Scribe服务器的实现:

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

我想要将一个通道(channel)传递给Log()函数,这样我就可以将scribe数据传递给一个单独的Go协程(goroutine),但我不确定如何修改scribe/thrift.go来扩展日志接口为:

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

(或者是否需要这样做,以及是否有一种方法可以在不干扰原始库的情况下扩展接口)。

英文:

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

得分: 10

你不能修改或扩展已经声明的接口,你只能创建一个新的接口,可能会扩展旧的接口。但是你不能在接口中重新声明方法。

这意味着你想要做的(修改Scribe接口,使其Log方法具有不同的签名)是不可能的。

你可以做的是创建一个类型,该类型持有你的通道,并嵌入你想要扩展的结构。

示例:

type Scribe interface {
    Log(Messages []*LogEntry) (ResultCode, error)
}

type ModifiedScribe struct {
    Scribe
    counts chan string
}

func (m *ModifiedScribe) Log(Messages []*LogEntry) (ResultCode, error) {
    // 使用 m.counts 做一些操作

    // 调用嵌入实现的 Log 方法
    return m.Scribe.Log(Messages)
}

上面的示例定义了一个结构体,它嵌入了一个 Scribe 并定义了自己的 Log 方法,利用了嵌入的 Scribe 的方法。这个结构体可以在期望 Scribe 的任何地方使用(因为它实现了 Scribe 接口),但它还持有额外的通道。

英文:

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.

huangapple
  • 本文由 发表于 2013年12月13日 09:30:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/20557579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定