目录
1.结构体匿名字段--方法继承
package main
import "fmt"
type A struct {
a int
}
type B struct {
A
}
func (a *A) SayHello() {
fmt.Println("hello world!")
}
func main() {
b := &B{}
b.SayHello()
}
[root@ol7-19 goroutine]# go run struct.go
hello world!
A结构体有方法SayHello(),B的匿名成员为A,所以B初始化后就可以直接调用 所有A的属性和方法,就和自己拥有一样。
如果增加一个B结构的同名方法,刚使用的是B的SayHello(),可以用来做基类。比如beego的controller。
func (a *BSayHello() {
fmt.Println("hello world!")
}
[root@ol7-19 goroutine]# go run struct.go
B hello world!