如何在Go中正确初始化嵌套结构体(nested struct)?
大家好!我是Go新手,在初始化嵌套结构体时遇到了问题。我正在编写一个用于天气API的小项目。
我有以下结构体:
```go
type WeatherResponse struct {
Location Location
Current CurrentWeather
}
type Location struct {
Name string
Country string
Lat float64
Lon float64
}
type CurrentWeather struct {
Temperature float64
Humidity int
Condition string
Wind WindInfo
}
type WindInfo struct {
Speed float64
Deg int
}
```
我尝试创建`WeatherResponse`实例并立即填充所有字段,但遇到了编译错误。我尝试了不同的方式:
```go
// 方式1 - 不工作
data := WeatherResponse{
Location.Name: "Moscow",
Location.Country: "Russia",
CurrentWeather.Temperature: 22.5,
}
// 方式2 - 也不工作
data := WeatherResponse{
Location{"Moscow", "Russia", 55.75, 37.62},
CurrentWeather{22.5, 60, "Clear", WindInfo{5.2, 18}},
}
```