dtm41506
dtm41506
2018-10-01 16:05

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

  • interface
已采纳

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条回答