go - 如何设计一个返回另一个只能紧急实现的接口(interface)类型的接口(interface)

标签 go interface architecture

简短前提: 我尝试设计一个包,其中包含填充同一组接口(interface)的多种类型,以及另一个使用这些接口(interface)的包。现在我很困惑如何实现返回另一种接口(interface)类型的接口(interface)。

更长: 更具体地说:我有两种协议(protocol)/消息类型(广播/直接),我希望能够将它们打包以通过 http/json 和 amqp/rabbit 进行传输。我的“传输”包(json 和 amqp)需要我的消息包(dm/广播)来履行/呈现一些信息:例如GetAddressNewResponse。对于NewResponse,我的消息格式从它的元信息中生成一个ResponseMessage。我的传输器知道如何将 GetAddress 转换为有用的路由信息​​。我的接口(interface)问题:现在我很困惑如何实现返回另一种接口(interface)类型的接口(interface)。

type Addresser interface {
    GetRecipientAddress() string
}

type Responder interface {
    NewResponse() (Responder, error)
}

type DM struct {
}

func (dm *DM) GetRecipientAddress() string {
    return ""
}

func (dm *DM) NewResponse() (*DM, error) {
    return dm, nil
}

只要我的 (dm *DM) NewResponse 返回 ResponderResponder 接口(interface)就已实现。当我返回满足 Responder*DM 时,*DM 不满足 Responder

我觉得这似乎是先有鸡还是先有蛋的问题,只要我返回*DM*DM就不能满足响应者,但“事实上”它实现了它。

这导致了我的假设:我尝试为接口(interface)的使用实现一个糟糕的设计。有人可以指出 golang-gurus 解决这个问题的方向吗?

我认为这可能是一个解决方案,但它似乎同样有缺陷

type AddressResponder interface {
    Addresser
    Responder
}

func (dm *DM) NewResponse() (AddressResponder, error) {
    return dm, nil
}

最佳答案

参见Type identity :

Two interface types are identical if they have the same set of methods with the same names and identical function types. Non-exported method names from different packages are always different. The order of the methods is irrelevant.

Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.

<小时/>

尝试this :

// NewResponse returns  (Responder, error)
func (dm *DM) NewResponse() (Responder, error) {
    return dm, nil
}

关于go - 如何设计一个返回另一个只能紧急实现的接口(interface)类型的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57816821/

相关文章:

entity-framework - CQRS 是 CRUD 的替代品吗?

go - Go 中的函数声明是否严格?

java - 定义接口(interface)和类的最佳/标准方法

architecture - 架构中粗粒度/细粒度的定义

c# - 我可以在没有泛型的情况下定义/约束成员实现两个接口(interface)吗?

java - 如何使用枚举作为接口(interface)中函数声明的参数?

php - 您将如何为这个应用程序建模?

go - 如何根据参数类型获取返回值?

正在测试 log.Fatalf?

go - 无法在 Go 应用程序的另一个包中使用函数