1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-15 02:02:27 +08:00

feat: add ToMap function

This commit is contained in:
dudaodong
2022-07-11 10:27:38 +08:00
parent 9cd8bfb8e0
commit d06cde3fcf
2 changed files with 30 additions and 0 deletions

View File

@@ -175,6 +175,17 @@ func ToPointer[T any](value T) *T {
return &value
}
// ToMap convert a slice or an array of structs to a map
func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V {
res := make(map[K]V, len(array))
for _, item := range array {
k, v := iteratee(item)
res[k] = v
}
return res
}
// StructToMap convert struct to map, only convert exported struct field
// map key is specified same as struct field tag `json` value
func StructToMap(value any) (map[string]any, error) {