当方法被重载时,Golang结构调用嵌入式类型方法 [英] Golang struct calling embedded type methods when method has been overloaded

查看:107
本文介绍了当方法被重载时,Golang结构调用嵌入式类型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力学习Go,并且我发现了一个很好的资源 $ b

下面给出了方法重载的例子:

pre> 包主
导入fmt

类型人类结构{
名称字符串
年龄类型
手机字符串
}


类型Employee结构{
Human
公司字符串
}

func(h *人)SayHi(){
fmt.Printf(我是%s,你可以打电话给我%s\\\
,h.name,h.phone)
}

func(e * Employee)SayHi(){
fmt.Printf(你好,我是%s,我在%s工作,打电话给%s\\\
,e.name,
e.company,e.phone)//是的,你可以在这里分成两行。

$ b $ func main(){
sam:= Employee {Human {Sam,45,111-888-XXXX},Golang Inc}
sam.SayHi()
}

是否可以调用base 结构的(人的)方法,例如。 sam.Human.SayHi()Downcasting不起作用(因为没有类型层次结构的权利?)

您可以访问通过使用嵌入类型名称的名称调用父成员的父结构的嵌入式结构。

  sam:=员工{人类{Sam,45岁,这是一口,所以它可能更容易展示它。 ),Golang Inc} 
sam.SayHi()//调用Employee.SayHi
sam.Human.SayHi()//调用Human.SayHi

输出

  Hi ,我是山姆,我在Golang Inc.工作。给我打电话111-888-XXXX 
我是山姆,你可以给我打电话111-888-XXXX


I am trying to learn Go, and I found a good resource here.

The example given on method overloading is reproduced below:

package main
import "fmt"

type Human struct {
    name string
    age int
    phone string
}


type Employee struct {
    Human 
    company string
}

func (h *Human) SayHi() {
    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}

func (e *Employee) SayHi() {
    fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
        e.company, e.phone) //Yes you can split into 2 lines here.
}

func main() {
    sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}
    sam.SayHi()
}

Is it possible to call the "base" struct's (Human's) methods, eg. sam.Human.SayHi() Downcasting doesn't work (because there is no type hierarchy right?)

解决方案

You can access the embedded struct of a parent struct by calling the member of the parent with the name of the embedded type's name. That's a mouthful, so it's probably easier to demonstrate it.

 sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}
 sam.SayHi() // calls Employee.SayHi
 sam.Human.SayHi() // calls Human.SayHi

Outputs

 Hi, I am Sam, I work at Golang Inc. Call me on 111-888-XXXX
 Hi, I am Sam you can call me on 111-888-XXXX

这篇关于当方法被重载时,Golang结构调用嵌入式类型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆