dongtan3395 2016-05-05 20:10
浏览 100
已采纳

在嵌入式功能中访问功能

First, I'm quite new to Go, so please forgive any lapses or errors in terminology. I suspect my lack of command with the terminology is also partially to blame for not finding an answer to the following question after many hours of looking.

In short, I would like the output of the following code to be

I am the Adult
I am the Child

Where instead the output is

I am the Adult
I am the Adult

Code:

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()
}

So in essence, though Introduce() is only implemented in the embedded type, Human, it calls sayName(), which is implemented in both the embedded type and the embedding type.

I understand that the current output is the way as it is because the embedded Human struct doesn't "know" it's embedded and thus could never call Child.sayName and would only call its own sayName() function.

Is there a way to instantiate a Human struct (or a struct embedding one) in which you can "replace" Human.sayName() with an alternate sayName() function?

  • 写回答

3条回答 默认 最新

  • dtfo55908 2016-05-05 20:42
    关注

    The way to get this kind of late-bound behavior is to use interfaces. If Introduce was a method on an interface that required a sayName method, then Human and Child would both satisfy that interface, and could Introduce themselves, and the proper sayName method would be called in either case, because it would be dispatched via the interface type, instead of via Human.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决