以下代码生成“prog.go:17: c.Test undefined (type Child has no field or method Test)”。 ( http://play.golang.org/p/g3InujEX9W )
package main
import "fmt"
type Base struct {
X int
}
func (b Base) Test() int {
return b.X
}
type Child Base
func main() {
c := Child{4}
fmt.Println(c.Test())
}
我意识到 Test
在技术上是在 Base
上定义的,但是 Child
应该继承那个方法吗?
最佳答案
在 go 中实现继承的方法是使用 struct embedding
和 anonymous struct members
。
Here is an adaption of your example .
阅读结构嵌入和 Go 的继承方法等 here
您遇到的行为符合预期并与 golang specification 同步,其中明确指出:
The method set of any type T consists of all methods with receiver type T. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T). Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set.
关于oop - Go中扩展类型的访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22441483/