1. type Student struct {
  2. id int
  3. name string
  4. age int
  5. }
  1. // 顺序初始化,每个成员必须初始化
  2. var s1 Student = Student{1, "mike", 18}
  3. // 指定成员初始化,没有初始化的成员自动赋值
  4. s1 := Student{name: "mike" }
  1. var s Student
  2. s.id = 1
  3. s.name = "mike"
  1. p2 := new(Student)
  2. p2.id = 1
  3. p2.name = "mike"

匿名字段

  1. type Person struct {
  2. name string
  3. sex byte
  4. age int
  5. }
  6. type Student struct {
  7. Person
  8. id int
  9. addr string
  10. }
  11. func main() {
  12. var s1 Student = Student{Person{"mike", 'm', 18}, 1, "bj"}
  13. s2 := Student{Person{"mike", 'm', 18}, 1, "bj"}
  14. s3 := Student{id: 1}
  15. }