How do I reference a field in the "AllData" struct below from the main "Forecast" struct? e.g if I wanted to reference "TemperatureMax from Forecast -> Daily?
type AllData struct {
Time float64 `json:"time"`
Summary string `json:"summary"`
Icon string `json:"icon"`
TemperatureMin float64 `json:"temperatureMin"`
TemperatureMinTime float64 `json:"temperatureMinTime"`
TemperatureMax float64 `json:"temperatureMax"`
}
type HourlyData struct {
Summary string `json:"summary"`
Icon string `json:"icon"`
Data []CurrentData `json:"data"`
}
type DailyData struct {
Summary string `json:"summary"`
Icon string `json:"icon"`
Data []AllData `json:"data"`
}
type Forecast struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Timezone string `json:"timezone"`
Offset int `json:"offset"`
Currently CurrentData `json:"currently"`
Hourly HourlyData `json:"hourly"`
Daily DailyData `json:"daily"`
Flags Flags `json:"flags"`
}
You can access an AllData
field from a Forecast
struct by providing an index into the Data
slice in DailyData
. Consider this stripped-down example of your question:
package main
import "fmt"
type AllData struct {
Summary string
}
type DailyData struct {
Data []AllData
}
type Forecast struct {
Daily DailyData
}
func main() {
a := AllData{"summary"}
s := []AllData{a}
d := DailyData{s}
f := Forecast{d}
val := f.Daily.Data[0].Summary
fmt.Println(val)
}
In main
, we read the Summary
field from the AllData
struct at index 0 of the DailyData
's Data
slice. This prints summary
to the console.
Optionally, we could access multiple AllData
structs by ranging over the slice in DailyData
:
func main() {
a1 := AllData{"summary1"}
a2 := AllData{"summary2"}
a3 := AllData{"hello"}
s := []AllData{a1, a2, a3}
d := DailyData{s}
f := Forecast{d}
for _, val := range f.Daily.Data {
fmt.Println(val.Summary)
}
}
The above prints:
summary1
summary2
hello