I'm relatively new to go, and I'm looking for a rough equivalent (library or implementation) of guava multimap's index method. It works as follow
It should do the following:
Given a slice of structs, construct a map from the common value to arrays of entries that share that value. For example:
Repetition struct {
ID int
Days int
Category string
}
reps := []Repetition{
Repetition{ID: 1, Day: 0, Category: "strength"},
Repetition{ID: 2, Day: 0, Category: "aerobic"}
Repetition{ID: 3, Day: 1, Category: "strength"}
Repetition{ID: 4, Day: 1, Category: "aerobic"}
}
result = indexByDay(reps)
where result is:
map[int][]Repetition{
0: []Repetition{Repetition{ID: 1, Day: 0, Category: "strength"}, Repetition{ID: 2, Day: 0, Category: "aerobic"}},
1: []Repetition{Repetition{ID: 3, Day: 1, Category: "strength"}, Repetition{ID: 4, Day: 1, Category: "aerobic"}}
}
The question is whether there are any built in or existing libraries that have methods like indexByDay (somehow generic enough for to be library code perhaps?)
Apologies if my map literal is hilariously incorrect. I'm still new to the language.
Eh this turned out to not be that hard:
func group(reps []lifting.Repetition) map[int][]Repetition {
m := make(map[civil.Date][]lifting.Repetition)
for _, rep := range reps {
value, present := m[rep.Day]
if !present {
m[rep.Day] = []lifting.Repetition{rep}
} else {
m[rep.Day] = append(value, rep)
}
}
return m
}