go的结构体可包含一个或者多个结构体,如果不给结构体命名的话,则该结构体隐式的继承了结构体的所有成员
这个结构体称为匿名字段
匿名字段示例:
package main import "fmt" type Person struct { id int name string } type Man struct { Person } type Woman struct { Person } func main() { m :=Man{Person{1,"tioncico"}} fmt.Println(m.name)//可直接调用Person的成员 fmt.Println(m.Person.name)//也可以通过结构体类型调用 }
输出:
GOROOT=/Users/tioncico/sdk/go1.17 #gosetup GOPATH=/Users/tioncico/go/pkg/mod #gosetup /Users/tioncico/sdk/go1.17/bin/go build -o /private/var/folders/08/hkdkrdpn4mbb\_4l5zbvrq0hh0000gp/T/\_\_\_go\_build\_main_go /Users/tioncico/GolandProjects/LearnGoProject/main.go #gosetup /private/var/folders/08/hkdkrdpn4mbb\_4l5zbvrq0hh0000gp/T/\_\_\_go\_build\_main_go tioncico tioncico
同时,如果结构体存在接收者方法,也可以直接调用:
package main import "fmt" type Person struct { id int name string } type Man struct { Person } type Woman struct { Person } func (self *Person) ToString() string { // receiver = &(Manager.User) return fmt.Sprintf("Person: %p, %v", self, self) } func main() { m :=Man{Person{1,"tioncico"}} fmt.Println(m.ToString())//可直接调用Person的方法 fmt.Println(m.Person.ToString())//也可以通过结构体类型调用 }
输出:
GOROOT=/Users/tioncico/sdk/go1.17 #gosetup GOPATH=/Users/tioncico/go/pkg/mod #gosetup /Users/tioncico/sdk/go1.17/bin/go build -o /private/var/folders/08/hkdkrdpn4mbb\_4l5zbvrq0hh0000gp/T/\_\_\_go\_build\_main_go /Users/tioncico/GolandProjects/LearnGoProject/main.go #gosetup /private/var/folders/08/hkdkrdpn4mbb\_4l5zbvrq0hh0000gp/T/\_\_\_go\_build\_main_go Person: 0xc00000c030, &{1 tioncico} Person: 0xc00000c030, &{1 tioncico}
如果继承Person的类继续声明接收者函数,就可以实现"类函数重写"的效果:
package main import "fmt" type Person struct { id int name string } type Man struct { Person } type Woman struct { Person } func (self *Person) ToString() string { // receiver = &(Manager.User) return fmt.Sprintf("Person: %p, %v", self, self) } func (self *Man) ToString() string { // receiver = &(Manager.User) return fmt.Sprintf("Man: %p, %v", self, self) } func main() { m :=Man{Person{1,"tioncico"}} fmt.Println(m.ToString())//调用Man本身的ToString fmt.Println(m.Person.ToString())//调用结构体的ToString }
输出:
GOROOT=/Users/tioncico/sdk/go1.17 #gosetup GOPATH=/Users/tioncico/go/pkg/mod #gosetup /Users/tioncico/sdk/go1.17/bin/go build -o /private/var/folders/08/hkdkrdpn4mbb\_4l5zbvrq0hh0000gp/T/\_\_\_go\_build\_main_go /Users/tioncico/GolandProjects/LearnGoProject/main.go #gosetup /private/var/folders/08/hkdkrdpn4mbb\_4l5zbvrq0hh0000gp/T/\_\_\_go\_build\_main_go Man: 0xc00000c030, &{{1 tioncico}} Person: 0xc00000c030, &{1 tioncico}