Go语言 之匿名字段创建与初始化
package main import ( "fmt" ) type Person struct { id int name string } // 匿名字段(Person)只有类型没有变量名称 type Student struct { Person scort float64 } func main() { //错误写法 var s Student = Student{scort: 99.9, Person{id: 1, name: "yy"}} //写法一 var s Student = Student{Person{1, "yy"}, 99} //写法二 var s1 Student s1.Person.id = 1 s1.Person.name = "yy" s2 := Student{Person{2, "yy2"}, 90} fmt.Println(s, s1, s2) }