I have two functions in Go that do almost the same thing. They take a fragment of structures that has an ID field and re-sort it into a map indexed by that field. Then they attach it to a field of another structure, which is also identified by an identifier.
Two functions do the same, but add to two different fields in the structure. I want the methods to be universal, but I'm not sure how to do this. I would expect this to be possible with a pointer, but I'm not sure how to do this.
Function 1:
func addPremiereDatesToMovies(m []Movie, pd []PremiereDate) ([]Movie, error) {
pds := make(map[int64][]PremiereDate)
for _, value := range pd {
pds[value.Id] = append(pds[value.Id], value)
}
for key, value := range m {
if _, ok := pds[value.Id]; !ok {
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)
for _, value := range g {
gs[value.Id] = append(gs[value.Id], value)
}
for key, value := range m {
if _, ok := gs[value.Id]; !ok {
m[key].Genres = []Genre{}
continue
}
m[key].Genres = gs[value.Id]
}
return m, nil
}
They seem to look very similar. I can do this, but I cannot figure out how to generally describe the "value.Id" field on line 11.
Thank.