英文:
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.Expr和exprNode。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论