我希望实现fmt.Stringer
接口(interface)的String
方法。但是,对于从 Node
派生的一组类型,它们的 String
实现将是它们必须提供的 Print
接口(interface)方法的包装器。如何为所有实现 Node
的类型自动提供 String
?如果我在某些基类上提供默认的 String
,我将失去对派生类型(以及接口(interface)方法 Print
)的访问权限。
type Node interface {
fmt.Stringer
Print(NodePrinter)
}
type NodeBase struct{}
func (NodeBase) String() string {
np := NewNodePrinter()
// somehow call derived type passing the NodePrinter
return np.Contents()
}
type NodeChild struct {
NodeBase
// other stuff
}
func (NodeChild) Print(NodePrinter) {
// code that prints self to node printer
}
最佳答案
去explicitly declares这是不可能的:
When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one.
对于解决方案,我推荐如下:
func nodeString(n Node) string {
np := NewNodePrinter()
// do stuff
n.Print(np)
return np.Contents()
}
// Now you can add String method to any Node in one line
func (n NodeChild) String() string { return nodeString(n) }
关于inheritance - 以另一个接口(interface)的形式实现一个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10494303/