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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?