普通结构体嵌套
普通结构体嵌套,嵌套结构体可以通过 .子变量.方法 的方式获取被嵌套的属性和方法
type Person struct {
name string
sex int
}
func (person *Person) getName() string {
return person.name
}
type Student struct {
person Person
work string
}
func (student *Student) workName() string {
return student.work
}
func TestStruct(t *testing.T) {
student := &Student{work:"game"}
student.person = Person{name:"yanghunahuan", sex:1}
t.Log(student.person.getName()) //yanghuanhuan
t.Log(student.person.sex) //1
}
匿名嵌套
匿名嵌套之后,嵌套者可以直接获取到被嵌套者的属性和方法
type Person struct {
name string
sex int
}
func (person *Person) getName() string {
return person.name
}
type Student struct {
Person
work string
}
func (student *Student) workName() string {
return student.work
}
func TestStruct(t *testing.T) {
student := &Student{work:"game"}
student.Person = Person{name:"yanghunahuan", sex:1}
t.Log(student.getName()) //yanghuanhuan
t.Log(student.sex) //1
}