介面是由它們的功能定義的,而不是由它們包含的資料定義的。我發現,這使得對于普通舊資料 (POD) 類難以模仿 C 樣式繼承。我能想到的唯一解決方案是實作一個對所有實作介面的結構什么都不做的方法。考慮以下帶有“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
}
這是好習慣嗎?
uj5u.com熱心網友回復:
正如@mkopriva 在評論中解釋的那樣,這種模式在標準庫中確實很常見,所以它可能是要走的路。參見例如ast.Expr和exprNode
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/432511.html
