dsfphczao23473056 2019-09-06 06:33 采纳率: 100%
浏览 83

如何设计一个接口,该接口返回只能满足紧急情况的另一种接口类型

Short premise: I try to design a package which holds several types fullfilling the same set of interfaces and another package working with these interfaces. Now I'm puzzled how to fulfill an interface returning another interface type.

longer: To be more specific: I've got two protocol / message types (broadcast / direct) which I want to be able to package to be transported by http/json and amqp/rabbit. My "transport"-packages (json and amqp) require my message-packages (dm/broadcast) to fulfill / present some information: e.g. GetAddress or NewResponse. For NewResponse my message format generates, out of it's metainformation,a ResponseMessage. My transporter knows how to translate GetAddress to a useful routing information. There is my interface problem: Now I'm puzzled how to fulfill an interface returning another interface type.

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
}

As long as my (dm *DM) NewResponse returns Responder the Responder interface is fulfilled. When I return *DM, which fulfills Responder, *DM doesn't fulfill Responder.

I kind of see that this seems to be an chicken or the egg problem, as long as I return *DM, *DM doesn't fulfill Responder, but "de facto" it fulfills it.

That leeds my to my assumption: I try to implement a bad design for the use of interfaces. Can somebody point me in the direction golang-gurus would solve this problem?

I thought maybe this could be a solution, but it seems to be just as flawed

type AddressResponder interface {
    Addresser
    Responder
}

func (dm *DM) NewResponse() (AddressResponder, error) {
    return dm, nil
}
  • 写回答

2条回答 默认 最新

  • dongtan9518 2019-09-06 06:58
    关注

    See 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.


    Try this:

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

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决