我已經遇到過幾次,它很容易解決,但我只是想知道當接口嵌入具有匹配方法簽名的接口時,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 有重復的方法。在我看來,編譯器解決這些方法相同且不存在沖突的事實是相當微不足道的,這將使這些模式更簡單。這里的解決方案很簡單,但會導致一些重復,如果嘗試從外部包包裝接口,情況會變得更糟。在嵌入接口時允許這種重復有什么缺點嗎,也許我低估了編譯器的復雜性?更新 大多數評論似乎忽略了一個事實,即我提供的只是接口(也許我仍然遺漏了一些東西),為了清楚起見,現在包含示例用法的實現
- 0 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消