github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xmap/maps.go (about) 1 package xmap 2 3 import ( 4 "reflect" 5 ) 6 7 func Keys(m interface{}) []interface{} { 8 rtype := reflect.ValueOf(m) 9 if rtype.Kind() == reflect.Ptr { 10 rtype = rtype.Elem() 11 } 12 keys := make([]interface{}, 0) 13 switch rtype.Kind() { 14 case reflect.Map: 15 values := rtype.MapKeys() 16 for _, v := range values { 17 keys = append(keys, v.Interface()) 18 } 19 case reflect.Struct: 20 for i := 0; i < rtype.NumField(); i++ { 21 keys = append(keys, rtype.Type().Field(i).Name) 22 } 23 } 24 return keys 25 } 26 27 func Values(v interface{}) []interface{} { 28 rtype := reflect.ValueOf(v) 29 if rtype.Kind() == reflect.Ptr { 30 rtype = rtype.Elem() 31 } 32 keys := make([]interface{}, 0) 33 switch rtype.Kind() { 34 case reflect.Map: 35 r := rtype.MapRange() 36 for r.Next() { 37 keys = append(keys, r.Value().Interface()) 38 } 39 case reflect.Struct: 40 for i := 0; i < rtype.NumField(); i++ { 41 keys = append(keys, rtype.Field(i).Interface()) 42 } 43 } 44 return keys 45 } 46 47 func Contains(v interface{}, x interface{}) bool { 48 rtype := reflect.ValueOf(v) 49 if rtype.Kind() == reflect.Ptr { 50 rtype = rtype.Elem() 51 } 52 switch rtype.Kind() { 53 case reflect.Map: 54 for _, t := range rtype.MapKeys() { 55 if t.Interface() == x { 56 return true 57 } 58 } 59 case reflect.Struct: 60 str, ok := x.(string) 61 if !ok { 62 return false 63 } 64 for i := 0; i < rtype.NumField(); i++ { 65 if rtype.Type().Field(i).Name == str { 66 return true 67 } 68 } 69 } 70 return false 71 }