map.go 994 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package dara
  2. import (
  3. "reflect"
  4. )
  5. type Entry struct {
  6. Key string
  7. Value interface{}
  8. }
  9. // toFloat64 converts a numeric value to float64 for comparison
  10. func Entries(m interface{}) []*Entry {
  11. v := reflect.ValueOf(m)
  12. if v.Kind() != reflect.Map {
  13. panic("Entries: input must be a map")
  14. }
  15. entries := make([]*Entry, 0, v.Len())
  16. for _, key := range v.MapKeys() {
  17. // 确保 Key 是字符串类型
  18. if key.Kind() != reflect.String {
  19. panic("Entries: map keys must be of type string")
  20. }
  21. value := v.MapIndex(key)
  22. entries = append(entries, &Entry{
  23. Key: key.String(),
  24. Value: value.Interface(),
  25. })
  26. }
  27. return entries
  28. }
  29. func KeySet(m interface{}) []string {
  30. v := reflect.ValueOf(m)
  31. if v.Kind() != reflect.Map {
  32. panic("KeySet: input must be a map")
  33. }
  34. keys := make([]string, 0, v.Len())
  35. for _, key := range v.MapKeys() {
  36. if key.Kind() != reflect.String {
  37. panic("KeySet: map keys must be of type string")
  38. }
  39. keys = append(keys, key.String())
  40. }
  41. return keys
  42. }