栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

GoLang中的继承和重写

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

GoLang中的继承和重写

  • 1、继承并调用父构造体的方法
  • 2、继承一个构造体并重写的情况
  • 3、继承多个构造体的情况
  • 4、继承接口的情况
  • 5、重载

1、继承并调用父构造体的方法

Dog 构造体继承 Animal 构造体,并且调用了 Animal 的方法

type Dog struct {
	Animal // 继承了Animal
}
type Animal struct {
}
func (a *Animal) Name() {
	fmt.Println("animal name is dog")
}
func main() {
	dog := Dog{}
	dog.Name() // 可以直接点出.Name()
	dog.Animal.Name() // 也可以点出父构造体
}

输出结果

animal name is dog
animal name is dog

2、继承一个构造体并重写的情况

Dog 构造体重写了 Animal 构造体,并且调用了 重写(override)后的方法

type Dog struct {
	Animal // 继承了Animal
}
func (d *Dog) Name() { // Dog 构造体重写了 Animal 构造体的 Name 方法
	fmt.Println("this is dog")
}
type Animal struct {
}
func (a *Animal) Name() {
	fmt.Println("animal name is dog")
}
func main() {
	dog := Dog{}
	dog.Name() // 此时方法被重写,执行了重写后的 Name() 方法
	dog.Animal.Name()
}

输出结果

this is dog
animal name is dog

3、继承多个构造体的情况

Dog 构造体继承 Animal 构造体以及 Life 构造体,在没有重写的情况下

type Dog struct {
	Animal // 继承了Animal
	Life   // 继承了Life
}
type Animal struct {
}
func (a *Animal) Name() {
	fmt.Println("animal name is dog")
}
type Life struct {
}
func (l *Life) Name() {
	fmt.Println("life name is bob")
}
func main() {
	dog := Dog{}
	dog.Name()
	dog.Animal.Name()
	dog.Life.Name()
}

此时编译会报错,IDEA会提示 “Ambiguous reference ‘Name’(含糊不清的参考“名称”)”


同时继承两个构造体时将无法直接调用父构造体的方法,必须调用父构造体后再调用其方法

4、继承接口的情况

Dog 构造体继承 Animal 接口

type Dog struct {
	Animal // 继承了Animal接口
}
type Animal interface {
	Name()
}
func main() {
	dog := Dog{}
	dog.Name()
}

输出结果

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x5b8c2e]

经过断点后查看到父构造体为空

5、重载

golang没有方法或函数的重载,引用golang官网的原文

如果方法分派也不需要进行类型匹配,则可以简化方法分派。 其他语言的经验告诉我们,使用具有相同名称但签名不同的多种方法有时会很有用,但在实践中也可能会造成混淆和脆弱。 在Go的类型系统中,仅按名称进行匹配并要求类型一致是简化的主要决定。

为什么Go不支持方法和运算符的重载?https://golang.google.cn/doc/faq#overloading

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908674.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号