123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- package services
- import (
- pkg "goiot-pkg/models"
- "reflect"
- )
- // 把结构体转换为Int
- func InterfaceToInt(data interface{}) int {
- if p, ok := data.(float64); ok {
- return int(p)
- }
- return 0
- }
- // 把结构体转换为Bool
- func InterfaceToBool(data interface{}) bool {
- if p, ok := data.(bool); ok {
- return p
- }
- return false
- }
- // 把结构体转换为Float32
- func InterfaceToFloat32(data interface{}) float32 {
- if p, ok := data.(float64); ok {
- return float32(p)
- }
- return 0.
- }
- // 把结构体转换为IntDic
- func InterfaceToIntDic(data interface{}) pkg.IntDic {
- value := reflect.ValueOf(data)
- if value.Kind() != reflect.Slice {
- return nil
- }
- var intDic = make(pkg.IntDic, 0)
- for i := 0; i < value.Len(); i++ {
- em := reflect.ValueOf(data).Index(i).Elem()
- if em.Kind() != reflect.Map {
- continue
- }
- intP := pkg.IntP{}
- for _, key := range em.MapKeys() {
- if p, ok := em.MapIndex(key).Interface().(string); ok {
- intP.Key = p
- } else if p, ok := em.MapIndex(key).Interface().(float64); ok {
- intP.Value = int(p)
- }
- }
- intDic = append(intDic, intP)
- }
- return intDic
- }
- // 把结构体转换为BoolDic
- func InterfaceToBoolDic(data interface{}) pkg.BoolDic {
- value := reflect.ValueOf(data)
- if value.Kind() != reflect.Slice {
- return nil
- }
- var boolDic = make(pkg.BoolDic, 0)
- for i := 0; i < value.Len(); i++ {
- em := reflect.ValueOf(data).Index(i).Elem()
- if em.Kind() != reflect.Map {
- continue
- }
- boolP := pkg.BoolP{}
- for _, key := range em.MapKeys() {
- if p, ok := em.MapIndex(key).Interface().(string); ok {
- boolP.Key = p
- } else if p, ok := em.MapIndex(key).Interface().(bool); ok {
- boolP.Value = p
- }
- }
- boolDic = append(boolDic, boolP)
- }
- return boolDic
- }
- // 把结构体转换为StringDic
- func InterfaceToStringDic(data interface{}) pkg.StringDic {
- value := reflect.ValueOf(data)
- if value.Kind() != reflect.Slice {
- return nil
- }
- var stringDic = make(pkg.StringDic, 0)
- for i := 0; i < value.Len(); i++ {
- em := reflect.ValueOf(data).Index(i).Elem()
- if em.Kind() != reflect.Map {
- continue
- }
- stringP := pkg.StringP{}
- for _, key := range em.MapKeys() {
- if p, ok := em.MapIndex(key).Interface().(string); ok {
- stringP.Key = p
- } else if p, ok := em.MapIndex(key).Interface().(string); ok {
- stringP.Value = p
- }
- }
- stringDic = append(stringDic, stringP)
- }
- return stringDic
- }
|