结构体 Struct
Definition
type authenticationInfo struct {
username string
password string
}
Nested Struct
type Address struct {
City, State string
}
type Person struct {
Name string
Address Address // 嵌套Address结构体
}
func main() {
p := Person{
Name: "Jane Doe",
Address: Address{
City: "Los Angeles",
State: "CA",
},
}
fmt.Println(p.Name) // Jane Doe
fmt.Println(p.Address.City) // Los Angeles
}
Embedded Struct
type Address struct {
City, State string
}
type Person struct {
Name string
Address // 嵌入Address结构体
}
func main() {
p := Person{
Name: "John Doe",
Address: Address{
City: "New York",
State: "NY",
},
}
fmt.Println(p.Name) // John Doe
fmt.Println(p.City) // New York (通过嵌入的Address访问)
fmt.Println(p.Address.City) // New York (通过Address字段访问)
}