使用普通的数据结构进行继承

huangapple go评论97阅读模式
英文:

Inheritance with plain old data structs

问题

接口的定义是根据它们的功能而不是它们包含的数据来确定的。我发现这使得模拟C++风格的继承对于Plain Old Data (POD)类变得困难。我能想到的唯一解决办法是为所有实现该接口的结构体实现一个什么都不做的方法。考虑下面的示例,其中包含了"fooSignatureMove":

package main

type foo interface{
   // fooSignatureMove什么都不做,只是允许模拟继承
   fooSignatureMove()
}

type A struct{}
type B struct{}
type C struct{}

func (*A) fooSignatureMove(){}
func (*B) fooSignatureMove(){}

func main(){
  arr := make([]foo, 2)
  arr[0] = &A{}
  arr[1] = &B{}
  arr[2] = &C{} // 我不希望这个能编译通过
}

这样做是否是一个好的实践?

英文:

Interfaces are defined by their functionality and not by the data they contain. This, I find, makes mimicking C++ style inheritance difficult for Plain Old Data (POD) classes. The only solution I can think of is to implement a method that does nothing for all struct that implement the interface. Consider the below example with "fooSignatureMove"

package main

type foo interface{
   // fooSignatureMove does nothing but allow to mimick inheritence
   fooSignatureMove()
}

type A struct{}
type B struct{}
type C struct{}

func (*A) fooSignatureMove(){}
func (*B) fooSignatureMove(){}


func main(){
  arr := make([]foo, 2)
  arr[0] = &A{}
  arr[1] = &B{}
  arr[2] = &C{} // I do not want this to compile
}

Is this good practice?

答案1

得分: 1

正如@mkopriva在评论中解释的那样,这种模式在标准库中确实非常常见,所以这可能是正确的方法。例如,可以参考ast.ExprexprNode

英文:

As @mkopriva explained in a comment, this pattern is indeed quite common in the standard library, so it is probably the way to go. See for example ast.Expr and exprNode

huangapple
  • 本文由 发表于 2022年2月20日 17:11:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/71192908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定