I wish to implement the fmt.Stringer interface’s String method. However for a set of types deriving from Node, their String implementations would be a wrapper around a Print interface method they must provide. How can I provide String automatically for all types implementing Node? If I provide the default String on some base class, I lose access to the derived type (and thus the interface method 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
}
Go explicitly declares that it’s not possible:
For a solution, I recommend something like this: