Go 嵌套结构体,有时候,数据结构需要包含多个层级。此时,虽然可选择使用诸如切片等数据类型,但有时候需要的数据结构更复杂。为建立较复杂的数据结构,在一个结构体中嵌套另一个结构体的方式很有用。一个这样的例子是超级英雄列表:对于每位超级英雄,都需要存储其住址,而住址本身也是一个数据结构,非常适合使用结构体来表示。
type Superhero struct {
Name string
Age int
Address Address
}
type Address struct {
Number int
Street string
City string
}
创建结构体Superhero的实例时,其中将包含一个数据字段为默认值的Address结构体。这可改善代码的灵活性和模块性,因为结构体Address也可用于其他地方。
可在创建Superhero结构体前创建Address结构体并给它赋值,但也可在创建Superhero结构体时这样做。如下程序使用简短变量赋值创建了一个嵌套结构体实例。
package main
import (
"fmt"
)
type Superhero struct {
Name string
Age int
Address Address
}
type Address struct {
Number int
Street string
City string
}
func main() {
e := Superhero{
Name: "Batman",
Age: 32,
Address: Address{
Number: 1007,
Street: "coolcou",
City: "Gotham",
},
}
fmt.Printf("%+v\n", e)
}
运行结果:
要访问内嵌结构体的数据字段,可使用点表示法,这意味着使用结构体变量名、圆点、数据字段名、圆点和内嵌数据字段名,如下所示。
fmt.Println(e.Address.Street)
酷客教程相关文章:
评论前必须登录!
注册