ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] # 匿名组合 ## 匿名字段 一般情况下,定义结构体的时候是字段名和其类型一一对应,实际上go支持**只提供类型而不写字段名的方法**,也就是匿名字段,也称为嵌入式字段 当匿名字段也是一个结构体的时候,那么这个结构体所拥有的全部字段都被隐式的引入了当前定义的这个结构体 实现代码复用 ~~~ type Person struct { id int name string sex byte //字符类型 age int } type Student struct { Person //匿名字段,默认Student就包含了Person的所有字段 id int addr string } ~~~ ~~~ func main() { //要加结构体名字里面 s := Student{Person{11, "mm"}, 11, "aaa"} // %v详细打印 fmt.Printf("s = %v\n", s) } ~~~ 输出 ~~~ s = {{11 mm} 11 aaa} ~~~ ## 显示赋值 ~~~ type Person struct { id int name string } type Student struct { Person //匿名字段,默认Student就包含了Person的所有字段 id int addr string } func main() { var s Student //默认是给本作用域,如果找不到找其他的 s.id = 1 //指定,显示调用 s.Person.id = 2 // %v详细打印 fmt.Printf("s = %v\n", s) } ~~~ ## 非结构体匿名字段 ~~~ type mystr string type Person struct { id int name string } type Student struct { Person //匿名字段,默认Student就包含了Person的所有字段 id int addr string mystr } func main() { var s Student //默认是给本作用域,如果找不到找其他的 s.id = 1 s.mystr = "111" //指定,显示调用 s.Person.id = 2 // %v详细打印 fmt.Printf("s = %v\n", s) } ~~~