首页 > 解决方案 > 冲突的匹配嵌入式接口方法是功能、错误还是其他?

问题描述

我已经遇到过几次并且很容易解决,但我只是想知道当接口嵌入具有匹配方法签名的接口时,Go 编译器是否有任何优势。

例如,如果我想要一个记录器的一些变化去不同的包,但最终我想使用同一个记录器,我可能会尝试这样的事情:

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{}) {}

这可以用作以下方法的参数:

func p1.RegisterLogger(l Logger){}

func p2.RegisterLogger(l DebugLogger){}

func p3.RegisterLogger(l ErrorLogger){}

func p4.RegisterLogger(l DebugErrorLogger){}

但这不起作用,因为编译器会抱怨 ErrorDebugLogger 有重复的方法。在我看来,对于编译器来说,解决这些方法相同且没有冲突这一事实将是相当微不足道的,这将使这些模式更简单。

这里的解决方案是微不足道的,但会导致一些重复,如果尝试从外部包包装接口,情况会变得更糟。

在嵌入接口时允许这种重复是否有任何不利之处,也许我低估了编译器的复杂性?

更新 大多数评论似乎都忽略了我提供的只是接口(也许我仍然缺少一些东西),为了清楚起见,现在包含在示例用法中的实现

标签: gointerface

解决方案


这个问题已经在这里讨论过:https ://github.com/golang/go/issues/6977

这里还有一个关于如何解决这个问题的问题,也许你会发现答案很有用:如何处理 Go 接口中的重复方法?


推荐阅读