go特性(组合)

 2023-09-05 阅读 81 评论 0

摘要:为什么80%的码农都做不了架构师?>>> go的组合功能,也可以说是继承 type People struct {Name stringAge int }type Student struct{PeopleNo int } 定义一个student的函数: func (this *Student) Print() {fmt.Println(this.Name,this.Age,th

为什么80%的码农都做不了架构师?>>>   hot3.png

go的组合功能,也可以说是继承

type People struct {Name stringAge int
}type Student struct{PeopleNo int
}

定义一个student的函数:

func (this *Student) Print()  {fmt.Println(this.Name,this.Age,this.No)
}

这样,student里面,就可以使用people的字段了,相当于是继承了People的属性.

不过,这里有个坑就是,不能再初始化的时候,直接使用people的属性。所以说,这个继承并不是JAVA里面的那种继承,是简化版的继承。

std:=&Student{Name:"qii",Age:18,No:2016001}//错误std:=&Student{People:People{Name:"qii",Age:18},No:2016001}//正确
//或者
people:=People{Name:"qii",Age:18}
std:=&Student{People:people,No:2016001}

方法也是继承的.

func (this *People)Hello()  {fmt.Println("hello,",this.Name)
}
std.Print()//qii 18 2016001
std.Hello()//hello, qii

需要说明的是,这里的this并不是关键字,可以替换为其他的任意变量名称。go里没有隐示的this指针变量。任何的引用,都需要显示的写出来。就比如括号里面的this *People.this 代表的就是Peope的指针,也可以写成p *People。

转载于:https://my.oschina.net/qii/blog/700437

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/1076.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息