英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论