mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-22 23:12:15 +08:00
docs: 嵌套结构体、匿名嵌套结构体
This commit is contained in:
parent
2444f78870
commit
c96b7cebe0
59
base/struct/nested/main.go
Normal file
59
base/struct/nested/main.go
Normal file
@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Person
|
||||
// 嵌套结构体
|
||||
type Person struct {
|
||||
Name string
|
||||
Age int
|
||||
Address Address
|
||||
}
|
||||
|
||||
// Person2
|
||||
// 匿名 嵌套结构体
|
||||
type Person2 struct {
|
||||
Name string
|
||||
Age int
|
||||
Address
|
||||
}
|
||||
|
||||
type Company struct {
|
||||
Name string
|
||||
Address Address
|
||||
}
|
||||
|
||||
type Address struct {
|
||||
Province string
|
||||
City string
|
||||
}
|
||||
|
||||
func main() {
|
||||
p1 := &Person{
|
||||
Name: "张三",
|
||||
Age: 20,
|
||||
Address: Address{
|
||||
Province: "广东",
|
||||
City: "广州",
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("%#v\n", p1)
|
||||
fmt.Printf("%v %v\n", p1.Address.Province, p1.Address.City)
|
||||
|
||||
fmt.Println("=========================================================")
|
||||
|
||||
p2 := &Person2{
|
||||
Name: "李四",
|
||||
Age: 20,
|
||||
Address: Address{
|
||||
Province: "广东",
|
||||
City: "广州",
|
||||
},
|
||||
}
|
||||
fmt.Printf("%#v\n", p2)
|
||||
fmt.Printf("%v %v\n", p2.Address.Province, p2.Address.City)
|
||||
// 匿名结构体 先在自己的 结构体中 寻找 字段 若 找不到 则 从 匿名嵌套结构体中 查找
|
||||
// 如果 多个匿名嵌套结构体中 有字段冲突 则只能使用 类型名.字段名 访问
|
||||
fmt.Printf("%v %v\n", p2.Province, p2.City)
|
||||
}
|
Loading…
Reference in New Issue
Block a user