Skip to content

Commit

Permalink
add MakeMaps function
Browse files Browse the repository at this point in the history
  • Loading branch information
ixiongjianbo committed Jun 6, 2023
1 parent 539a4c3 commit a1fe23b
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,31 @@ func MakeMap[KeyType KeyTypeDef, ItemType any](slice []ItemType, field string) m
}
return result
}

func MakeMaps[KeyType KeyTypeDef, ItemType any](slice []ItemType, field string) map[KeyType][]ItemType {
result := make(map[KeyType][]ItemType)
for _, elem := range slice {
v := reflect.ValueOf(elem)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() == reflect.Struct {
t := v.Type()
index := -1
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Name == field || f.Tag.Get("json") == field {
index = i
break
}
}
if index >= 0 {
key := v.Field(index).Interface()
if convertKey, ok := key.(KeyType); ok {
result[convertKey] = append(result[convertKey], elem)
}
}
}
}
return result
}

0 comments on commit a1fe23b

Please sign in to comment.