我正在尝试学习Go,并且在这里找到了很好的资源。
下面给出了有关方法重载的示例:
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()
}
是否可以调用“基本”结构的(人类)方法,例如。sam.Human.SayHi()向下转换不起作用(因为没有正确的类型层次结构?)
您可以通过使用嵌入类型名称的名称调用父级成员来访问父级结构的嵌入结构。那是一个大嘴巴,所以可能更容易证明。
sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}
sam.SayHi() // calls Employee.SayHi
sam.Human.SayHi() // calls Human.SayHi
产出
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句