普通結(jié)構(gòu)體嵌套
普通結(jié)構(gòu)體嵌套阳柔,嵌套結(jié)構(gòu)體可以通過 .子變量.方法 的方式獲取被嵌套的屬性和方法
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
}