在接口定义中,可以使用多个方法吗?

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

are multiple methods ok in an interface definition?

问题

在Go语言中构建接口的常见示例如下:

type Notifier interface {
    Notify()
}

文档似乎说...在类型名称后面添加动词的“er”版本。现在,由于方法名和接口名相似,在定义中有多个方法可能没有意义。

我尝试过:

type Commander interface {
    Command()
    Notify()
}

它以你所期望的奇怪方式工作,但似乎不正确,并且没有任何阻止我这样做的东西。我只是不确定是否应该链接这些命令以及在代码中更深层次的实现会是什么样子。

type Commander interface {
    Command()
}

type Notifier interface {
    Notify()
}

但是,通过调用我的函数:

DoStuff(c, n)

当一个实现了两个接口的单个参数也是有意义的。

英文:

when building an interface in go the common example looks like:

type Notifier interface {
    Notify()
}

The doc sees to say stuff like... add the 'er' version of the verb to the type name. Now since the method name and the interface name are similar having multiple methods in the definition would not makes sense.

I'm trying:

type Commander interface {
    Command()
    Notify()
}

it works in all the odd ways you'd expect but it seems wrong and there is nothing preventing me from doing this. I'm just not sure if I should be chaining the commands and what that might look like deeper in the code.

type Commander interface {
    Command()
}

type Notifier interface {
    Notify()
}

But the idea of calling my function:

DoStuff(c, n)

when a single param that implements both interfaces would make sense too.

答案1

得分: 4

这是完全可以的,并且在标准库中也有几个地方可以看到(例如:http://golang.org/pkg/io/#ReadWriter)。

它们是否应该放在一个接口中还是两个接口中,取决于是否有意义或者是否有用,有一个类型实现其中一个接口但不实现另一个接口。

英文:

That's perfectly fine, and it shows up in the standard library in a few places as well (e.g. http://golang.org/pkg/io/#ReadWriter).

Whether they should be in a single interface or two interfaces depends on if it makes sense or is ever useful to have a type implementing one but not the other.

答案2

得分: 3

一种方法是像标准库中的ReadWriter案例那样进行操作。

首先定义一个接口:

type Commander interface {
    Command()
}

然后定义另一个接口:

type Notifier interface {
    Notify()
}

接下来定义你想要作为参数的类型:

type CommandNotifier interface {
    Commander
    Notifier
}

最后定义你的函数:

func DoStuff(cn CommandNotifier) {
    // TODO - 做一些操作
}
英文:

One approach would be to do it like the ReadWriter case in the standard library.

Define one interface:

type Commander interface {
    Command()
}

and the other:

type Notifier interface {
    Notify()
}

and then the type you want as a parameter:

type CommandNotifier interface {
    Commander
    Notifier
}

and finally define your function:

func DoStuff(cn CommandNotifier) {
    // TODO - do stuff
}

huangapple
  • 本文由 发表于 2014年5月26日 10:06:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/23861791.html
匿名

发表评论

匿名网友

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

确定