为什么80%的码农都做不了架构师?>>>
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。