fmt_plus.go 964 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package utils
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. //@author: [piexlmax](https://github.com/piexlmax)
  8. //@function: StructToMap
  9. //@description: 利用反射将结构体转化为map
  10. //@param: obj interface{}
  11. //@return: map[string]interface{}
  12. func StructToMap(obj interface{}) map[string]interface{} {
  13. obj1 := reflect.TypeOf(obj)
  14. obj2 := reflect.ValueOf(obj)
  15. var data = make(map[string]interface{})
  16. for i := 0; i < obj1.NumField(); i++ {
  17. if obj1.Field(i).Tag.Get("mapstructure") != "" {
  18. data[obj1.Field(i).Tag.Get("mapstructure")] = obj2.Field(i).Interface()
  19. } else {
  20. data[obj1.Field(i).Name] = obj2.Field(i).Interface()
  21. }
  22. }
  23. return data
  24. }
  25. //@author: [piexlmax](https://github.com/piexlmax)
  26. //@function: ArrayToString
  27. //@description: 将数组格式化为字符串
  28. //@param: array []interface{}
  29. //@return: string
  30. func ArrayToString(array []interface{}) string {
  31. return strings.Replace(strings.Trim(fmt.Sprint(array), "[]"), " ", ",", -1)
  32. }