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?

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

报告相同问题?

悬赏问题

  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题