Access method of extended type in Go

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

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.

huangapple
  • 本文由 发表于 2014年3月17日 03:07:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/22441483.html
匿名

发表评论

匿名网友

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

确定