Go語言 - 結構體

Go語言的結構體跟C語言的結構體有點相似,不過定義方法有點區別。ide

結構體定義:指針

type person struct {
  name string
  age  int8
}

結構體初始化:code

p0 := person{"Hi", 18}
p1 := person{name: "Go", age: 19}
p2 := new(person) // 指針
p2.name = "Gooo"
p2.age = 20
var p3 person
p3.name = "Goooo!"
p3.age = 21
fmt.Println(p0)
fmt.Println(p1)
fmt.Println(p2)
fmt.Println(p3)

結構體嵌套:string

type person struct {
  name string
  age  int8
  ddd  birthday // 嵌套
}

type birthday struct {
  year  int16
  month int8
  day   int8
}

結構體嵌套初始化:it

p0 := person{name: "Hi", age: 18, ddd: birthday{year: 2021, month: 9, day: 30}}
fmt.Println(p0.ddd.year) // persion.birthday.year

結構體匿名嵌套:io

type person struct {
  name string
  age  int8
  birthday // 匿名嵌套
}

type birthday struct {
  year  int16
  month int8
  day   int8
}

結構體匿名嵌套初始化:class

p0 := person{name: "Hi", age: 18, birthday: birthday{year: 2021, month: 9, day: 30}} // 這裏再也不是ddd,而是birthday
fmt.Println(p0.year) // 這裏直接 persion.year

注意多個匿名嵌套存在字段同名會衝突,若是結構體會在別的包使用須要首字母大寫(字段也是)方法

相關文章
相關標籤/搜索