map.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package utils
  2. import (
  3. "reflect"
  4. "sort"
  5. "strconv"
  6. "golang.org/x/exp/constraints"
  7. )
  8. // MapValues 获取Map中所有的Key,作为切片返回,可排序
  9. func MapValues[K constraints.Ordered, V any](m map[K]V, order bool) []V {
  10. values := make([]V, 0, len(m))
  11. if !order {
  12. for _, v := range m {
  13. values = append(values, v)
  14. }
  15. } else {
  16. keys := MapKeys(m, true)
  17. for i := 0; i < len(keys); i++ {
  18. values = append(values, m[keys[i]])
  19. }
  20. }
  21. return values
  22. }
  23. // MapKeys 获取Map中所有的Value,作为切片返回,可排序
  24. func MapKeys[K constraints.Ordered, V any](m map[K]V, order bool) []K {
  25. keys := make([]K, 0, len(m))
  26. for k := range m {
  27. keys = append(keys, k)
  28. }
  29. if order {
  30. sort.SliceStable(keys, func(i, j int) bool {
  31. return keys[i] < keys[j]
  32. })
  33. }
  34. return keys
  35. }
  36. // Slice2Map 切片转化为map,map的key从1开始累加
  37. func Slice2Map[T any](s []T) map[int64]T {
  38. m := make(map[int64]T, len(s))
  39. for i, v := range s {
  40. m[int64(i+1)] = v
  41. }
  42. return m
  43. }
  44. // ArrayColumns 参照php ArrayColumns
  45. func ArrayColumns[T any](input []T, column string) map[string]T {
  46. var output = make(map[string]T, len(input))
  47. var key string
  48. if len(input) < 1 {
  49. return output
  50. }
  51. immutableT := reflect.TypeOf(input[0])
  52. field, ok := immutableT.FieldByName(column)
  53. if !ok {
  54. return output
  55. }
  56. for _, row := range input {
  57. switch field.Type.Kind() {
  58. case reflect.String:
  59. key = reflect.ValueOf(row).FieldByName(column).Interface().(string)
  60. case reflect.Int64:
  61. tk := reflect.ValueOf(row).FieldByName(column).Interface().(int64)
  62. key = strconv.Itoa(int(tk))
  63. case reflect.Int:
  64. tk := reflect.ValueOf(row).FieldByName(column).Interface().(int)
  65. key = strconv.Itoa(tk)
  66. }
  67. output[key] = row
  68. }
  69. return output
  70. }