I have two functions in Go that do almost the same. They take a slice of structs which has an 'ID' field, and re-sort it into a map indexed by that field. They then append it to a field of another struct, which is also identified by the ID.
The two functions do the same, but append to two different fields in the struct. I want to make the methods generic, but I am not sure how to do it. I would expect it could be done using a pointer, but I'm not sure how.
Function 1:
func addPremiereDatesToMovies(m []Movie, pd []PremiereDate) ([]Movie, error) {
pds := make(map[int64][]PremiereDate)
// Key-index the premiere-date array for easier lookup
for _, value := range pd {
pds[value.Id] = append(pds[value.Id], value)
}
// Append premiere dates to movies where such exist
for key, value := range m {
if _, ok := pds[value.Id]; !ok { // <-- How to make this generic?
m[key].PremiereDates = []PremiereDate{}
continue
}
m[key].PremiereDates = pds[value.Id]
}
return m, nil
}
Function 2:
func addGenresToMovies(m []Movie, g []Genre) ([]Movie, error) {
gs := make(map[int64][]Genre)
// Key-index the genre array for easier lookup
for _, value := range g {
gs[value.Id] = append(gs[value.Id], value)
}
// Append genres to movies where such exist
for key, value := range m {
if _, ok := gs[value.Id]; !ok { // <-- How to make this generic?
m[key].Genres = []Genre{}
continue
}
m[key].Genres = gs[value.Id]
}
return m, nil
}
As it seems, they look quite similar. I am able to sort of do it, except I cannot figure out how to generically describe the "value.Id" field on line 11.
Thank you.