挑选结构体中的部分结构体
时间: 2023-10-22 19:08:07 浏览: 22
可以通过以下两种方法来挑选结构体中的部分结构体:
1. 使用嵌套结构体:在结构体中定义另一个结构体,然后在需要的地方使用该结构体的部分字段。
```go
type Person struct {
Name string
Age int
Address struct {
City string
Country string
}
}
func main() {
p := Person{
Name: "John",
Age: 30,
Address: struct {
City string
Country string
}{
City: "New York",
Country: "USA",
},
}
fmt.Println(p.Name)
fmt.Println(p.Address.City)
}
```
2. 使用匿名结构体:在需要的地方直接定义一个匿名结构体,并设置其字段值。
```go
type Person struct {
Name string
Age int
Address struct {
City string
Country string
}
}
func main() {
p := Person{
Name: "John",
Age: 30,
Address: struct {
City string
Country string
}{
City: "New York",
Country: "USA",
},
}
addr := struct {
City string
}{
City: p.Address.City,
}
fmt.Println(p.Name)
fmt.Println(addr.City)
}
```