1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package utils
- import (
- "reflect"
- "strconv"
- )
- func InterfaceToMap(data interface{}) map[string]interface{} {
- t := reflect.TypeOf(data)
- v := reflect.ValueOf(data)
- if v.Kind() != reflect.Struct {
- return nil
- }
- fieldNum := t.NumField()
- result := make(map[string]interface{})
- for i := 0; i < fieldNum; i++ {
- kind := t.Field(i).Type.Kind()
- if kind == reflect.Array || kind == reflect.Slice || kind == reflect.Struct {
- continue
- }
- result[t.Field(i).Name] = v.Field(i).Interface()
- }
- return result
- }
- // InterfaceToInt 把结构体转换为Int
- func InterfaceToInt(data interface{}) int {
- if p, ok := data.(string); ok {
- intVal, _ := strconv.Atoi(p)
- return intVal
- } else if p, ok := data.(int64); ok {
- return int(p)
- } else if p, ok := data.(float64); ok {
- return int(p)
- }
- return 0
- }
- // InterfaceToFloat64 把结构体转换为Float
- func InterfaceToFloat64(data interface{}) float64 {
- if p, ok := data.(string); ok {
- floatVal, _ := strconv.ParseFloat(p, 10)
- return floatVal
- } else if p, ok := data.(int64); ok {
- return float64(p)
- } else if p, ok := data.(float64); ok {
- return p
- }
- return 0.0
- }
|