英文:
Access method of extended type in Go
问题
以下是翻译好的内容:
以下代码会产生错误信息:"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
应该继承该方法吗?
英文:
The follow codes produces "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())
}
I realize Test
is technically defined on Base
, but should Child
inherit that method?
答案1
得分: 6
在Go语言中,使用struct嵌入
和匿名结构成员
是实现继承的方式。
这是你示例的一个改编版本。
阅读有关struct嵌入和Go语言继承等的更多信息,请点击这里。
你遇到的行为是符合预期的,并且与golang规范保持一致,该规范明确指出:
任何类型T的方法集由所有接收者类型为T的方法组成。相应指针类型T的方法集是所有接收者类型为T或T的方法集(即它还包含T的方法集)。对于包含匿名字段的结构体,还有其他规则,详见结构体类型的章节。任何其他类型都具有空的方法集。
英文:
the way to go for inheritance in go is using struct embedding
with anonymous struct members
.
Here is an adaption of your example.
Read about struct embedding and go's approach to inheritance etc here
The behaviour you encountered is expected and in sync with the golang specification, which explicitly states that:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论