1、是什么?
OOP:面向对象
Go语言的解构体嵌套
1、模拟集成性:is - a
type A struct {
field
}
type B struct {
A // 匿名字段
}
这种方式就会存在变量提升
2、模拟聚合关系:has - a
type C struct {
field
}
type D struct {
c C // 聚合关系
}
这种方式就需要访问结构体变量来设置相应的值
2、代码示例
/**
* @author ly (个人博客:https://www.cnblogs.com/ybbit)
* @date 2023/9/25 23:17
* @tags 喜欢就去努力的争取
*/
package main
import "fmt"
func main() {
p1 := Person{name: "张三", age: 18}
fmt.Println(p1)
s1 := Student{Person: Person{name: "ly", age: 20}, school: "北京大学", name: "小明"}
fmt.Println(s1)
var s2 Student
s2.Person.name = "李四"
s2.Person.age = 22
s2.school = "清华大学"
s2.name = "小花"
fmt.Println(s2)
var s3 Student
s3.Person.name = "王五"
s3.age = 23
s3.school = "武汉大学"
s3.name = "小张"
fmt.Println(s3)
}
type Person struct {
name string
age int
}
type Student struct {
Person
school string
name string
}
标签:24,struct,s3,s2,Person,OOP,Go,type,name
From: https://www.cnblogs.com/ybbit/p/17729157.html