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