go - 访问嵌入式函数中的函数

标签 go

首先,我是 Go 的新手,所以请原谅术语中的任何失误或错误。我怀疑我对术语的缺乏掌握也部分归咎于在查找了许多小时后没有找到以下问题的答案。

简而言之,我希望以下代码的输出是

I am the Adult
I am the Child

输出在哪里

I am the Adult
I am the Adult

代码:

package main

import "fmt"

type Human struct {
    age  uint
    name string
}

func (h Human) sayName() error {
    fmt.Println("I am the Adult")
    return nil
}

func (h Human) Introduce() error {
    h.sayName()
    return nil
}

type Child struct {
    Human
}

func (c Child) sayName() error {
    fmt.Println("I am the Child")
    return nil
}

func main() {
    h := Human{}
    h.Introduce()

    c := Child{Human{}}
    c.Introduce()
}

所以本质上,虽然 Introduce() 只在嵌入类型 Human 中实现,但它调用了 sayName(),它在嵌入类型和嵌入类型中都实现了。

我知道当前的输出是这样的,因为嵌入的 Human 结构不“知道”它是嵌入的,因此永远不会调用 Child.sayName 并且只会调用它自己的 sayName() 函数。

有没有一种方法可以实例化一个 Human 结构(或一个结构嵌入结构),您可以在其中用另一个 sayName() 函数“替换”Human.sayName()?

最佳答案

获得这种后期绑定(bind)行为的方法是使用接口(interface)。如果 Introduce 是接口(interface)上的一个方法,需要一个 sayName 方法,那么 HumanChild 都会满足接口(interface),并且可以 Introduce 自己,并且在任何一种情况下都会调用正确的 sayName 方法,因为它将通过接口(interface)类型而不是通过 Human

关于go - 访问嵌入式函数中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37059377/

相关文章:

go - Windows exec runner 无法克隆 git repo

go - Go 中的字节是否可以使用 nil 值?

mysql - 结构用户 - 有很多 session 。查找给定 session 的用户

arrays - 在 Golang 中将两个或多个 []map[string]interface{} 类型合并为一个

windows-8 - pprof 堆报告显示原始内存地址

go - 如何使用 Golang 向 LDAP 服务器添加新条目?

python - 保存使用 keras 训练的 TF 模型,然后在 Go 中进行评估

c++ - “vector <int> adj [10]”的替代品

python - 写入后无法使用 go 从文件中读取字节

go - 通过 channel 传递的消息是否保证是非阻塞的?