【问题标题】:Combining or extending interfaces?组合或扩展接口?
【发布时间】:2017-03-15 22:20:40
【问题描述】:

我有两个接口:

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

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

我想做一个结合了这两者的RequestResponder 接口。这可能吗,还是我必须创建一个包含所有 6 个功能的第三个接口?

【问题讨论】:

标签: go interface


【解决方案1】:

允许接口嵌入,如 spec 中所述:

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

这是在整个 Go 的标准库中完成的(一个例子是 io.ReadCloser)。

在您的问题中,RequestResponder 将被构造为:

type RequestResponder interface {
    Request
    Responder
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    相关资源
    最近更新 更多