inheritance - 以另一个接口(interface)的形式实现一个接口(interface)

标签 inheritance interface struct go base-class

我希望实现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/

相关文章:

interface - 是否可以在接口(interface)定义中使用 getter/setter?

c# - 接口(interface)和继承

arrays - 如何在golang的循环中删除结构数组的元素

声明结构时的 C++ 问题

C# 转换问题 : from IEnumerable to custom type

c# - 是否有一种紧凑的方式告诉 C# 编译器使用基本的 Equals 和 == 运算符?

c++ - 新类型(抽象类)

java - Parcelable 继承 : abstract class - Which CREATOR?

scala - Scala 中的可交换特性

javascript - 与 Java 一样,Object.call 也应该是 Javascript 构造函数中的第一个调用吗?