在嵌入式功能中访问功能

大卫:

首先,我刚接触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()?

滚刀:

获得这种后期绑定行为的方法是使用接口。如果Introduce接口上的sayName方法需要一个方法,则Human并且Child都将满足该接口,并且可能会Introduce自己使用,并且sayName在两种情况下都将调用适当的方法,因为它将通过接口类型而不是via调度Human

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章