oop - Go中扩展类型的访问方法

标签 oop inheritance 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 应该继承那个方法吗?

最佳答案

在 go 中实现继承的方法是使用 struct embeddinganonymous struct membersHere 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/

相关文章:

python - 一个Python类可以不继承多个类,而是有一个 "choice"的继承吗?

java - 覆盖父类的特定行

json - 在 struct 标签中使用变量

c++ - 如何在C++中制作类列表

c# - 为什么继承不像我认为的那样起作用?

java - 访问随机分配的对象

sockets - UDP SetWriteBuffer 和 SetReadBuffer 如何处理操作系统的缓冲区?

arrays - 复制go slices键值

c++ - 将函数的声明设置为 0 是什么意思?如何将整数分配给函数?

C++ - 定义 - 私有(private)继承