合并或扩展接口?

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

Combining or extending interfaces?

问题

我有两个接口:

type Request interface {
    Version() string
    Method() string
    Params() interface{}
    Id() interface{}
}

type Responder interface {
    NewSuccessResponse() Response
    NewErrorResponse() Response
}

我想创建一个RequestResponder接口,将这两个接口合并在一起。这可行吗,还是我必须创建一个包含所有6个函数的第三个接口?

英文:

I have two interfaces:

type Request interface {
    Version() string
    Method() string
    Params() interface{}
    Id() interface{}
}

type Responder interface {
    NewSuccessResponse() Response
    NewErrorResponse() Response
}

I would like to make a RequestResponder interface which combines both of these. Is this possible, or do I have to create a third interface with all 6 functions?

答案1

得分: 5

接口嵌入是允许的,如规范所述:

接口T可以在方法规范的位置使用一个(可能是限定的)接口类型名E。这被称为在T中嵌入接口E;它将E的所有(导出和非导出)方法添加到接口T中。

这在Go标准库中被广泛应用(一个例子是io.ReadCloser)。

在你的问题中,RequestResponder可以这样构建:

type RequestResponder interface {
    Request
    Responder
}
英文:

Interface embedding is allowed, as documented in the spec:

> An interface T may use a (possibly qualified) interface type name E in place of a method specification. This is called embedding interface E in T; it adds all (exported and non-exported) methods of E to the interface T.

This is done throughout Go's standard library (one example is io.ReadCloser).

In your question, RequestResponder would be constructed as:

type RequestResponder interface {
    Request
    Responder
}

huangapple
  • 本文由 发表于 2017年3月16日 06:20:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/42821792.html
匿名

发表评论

匿名网友

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

确定