I have the following structs defined for movies and TV shows:
type Movie struct {
ID string `json:"id"`
Viewers int `json:"count"`
}
type TVShow struct {
ID string `json:"id"`
Season int `json:"season"`
Episode int `json:"episode"`
Viewers int `json:"count"`
}
Then I have the following structs that contain several movies or TV shows by country:
type Movies struct {
PenultimateMonth map[string][]Movie
LastMonth map[string][]Movie
}
type TVShows struct {
PenultimateMonth map[string][]TVShow
LastMonth map[string][]TVShow
}
Finally, I have a data struct that holds everything:
type Data struct {
Movies Movies
Seasons Seasons
}
What I need to do is collect all IDs of all movies and TV shows from penultimate and last month.
I figured out that I can use reflection for that, but I only managed to iterate over each Data
element individually instead of all:
func GetIDs(data *Data, country string) []string {
var ids []string
movies := reflect.ValueOf(data.Movies).Elem()
tvShows := reflect.ValueOf(data.TVShows).Elem()
for i := 0; i < movies.NumField(); i++ {
moviesSubset := movies.Field(i).Interface().(map[string][]Movie)
for _, movie := range moviesSubset[country] {
ids = append(ids, movie.ID)
}
}
for i := 0; i < tvShows.NumField(); i++ {
tvShowsSubset := tvShows.Field(i).Interface().(map[string][]TVShow)
for _, tvShow := range tvShowsSubset[country] {
ids = append(ids, tvShow.ID)
}
}
return ids
}
Is it possible to simplify the GetIDs
function so that I don't need the two separate blocks for movies and TV shows, but only one to collect all IDs?