dtm41506 2018-10-01 16:05
浏览 31
已采纳

冲突的匹配嵌入式接口方法是功能,错误还是其他功能?

I've run into this a few times and its easy to work around but I'm just wondering if there are any advantages to the Go compiler complaining when interfaces embed interfaces with matching method signatures.

For example, if I want a few variations on a logger going to different packages but ultimately I want to use the same logger I might try something like this:

type Logger interface {
    Print(v ...interface{})
    Printf(format string, v ...interface{})
}

type DebugLogger interface {
    Logger
    Debug(v ...interface{})
    Debugf(format string, v ...interface{})
}

type ErrorLogger interface {
    Logger
    Error(v ...interface{})
    Errorf(format string, v ...interface{})
}

type ErrorDebugLogger interface {
    ErrorLogger
    DebugLogger
}

type ErrorDebugLoggerImp struct{}
func (l *ErrorDebugLoggerImp) Debug(v ...interface{})                 {}
func (l *ErrorDebugLoggerImp) Debugf(format string, v ...interface{}) {}
func (l *ErrorDebugLoggerImp) Error(v ...interface{})                 {}
func (l *ErrorDebugLoggerImp) Errorf(format string, v ...interface{}) {}
func (l *ErrorDebugLoggerImp) Print(v ...interface{})                 {}
func (l *ErrorDebugLoggerImp) Printf(format string, v ...interface{}) {}

and this could be used as a param to the following methods:

func p1.RegisterLogger(l Logger){}

func p2.RegisterLogger(l DebugLogger){}

func p3.RegisterLogger(l ErrorLogger){}

func p4.RegisterLogger(l DebugErrorLogger){}

But this won't work because the compiler will complain that ErrorDebugLogger has duplicate methods. It seems to me that this would be fairly trivial for the compiler to resolve the fact that these methods are identical and there is no conflict and this would make these kind of patterns simpler.

Here the solution is trivial but results in some duplication which gets worse if trying to wrap interfaces from external packages.

Is there any down side to allowing this kind of duplication when embedding interfaces, perhaps I am underestimating the complexity for the compiler?

UPDATE Most of the comments seemed to miss the fact that all I had provided were interfaces (maybe Im still missing something), implementation now included with example usage for clarity

  • 写回答

1条回答 默认 最新

  • douzi115522 2018-10-01 23:20
    关注

    This issue has been discussed here: https://github.com/golang/go/issues/6977

    There's also a question here on SO about how to address the issue, maybe you'll find the answer useful: How to deal with duplicate methods in Go interface?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)