Go语言 - 结构体
作者:互联网
Go语言的结构体跟C语言的结构体有点类似,不过定义方法有点区别。
结构体定义:
type person struct {
name string
age int8
}
结构体初始化:
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)
结构体嵌套:
type person struct {
name string
age int8
ddd birthday // 嵌套
}
type birthday struct {
year int16
month int8
day int8
}
结构体嵌套初始化:
p0 := person{name: "Hi", age: 18, ddd: birthday{year: 2021, month: 9, day: 30}}
fmt.Println(p0.ddd.year) // persion.birthday.year
结构体匿名嵌套:
type person struct {
name string
age int8
birthday // 匿名嵌套
}
type birthday struct {
year int16
month int8
day int8
}
结构体匿名嵌套初始化:
p0 := person{name: "Hi", age: 18, birthday: birthday{year: 2021, month: 9, day: 30}} // 这里不再是ddd,而是birthday
fmt.Println(p0.year) // 这里直接 persion.year
注意多个匿名嵌套存在字段同名会冲突,如果结构体会在别的包使用需要首字母大写(字段也是)
标签:语言,age,name,person,birthday,year,Go,int8,结构 来源: https://www.cnblogs.com/itqn/p/15056185.html