gutil_struct.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gutil
  7. import (
  8. "github.com/gogf/gf/util/gconv"
  9. "reflect"
  10. )
  11. // StructToSlice converts struct to slice of which all keys and values are its items.
  12. // Eg: {"K1": "v1", "K2": "v2"} => ["K1", "v1", "K2", "v2"]
  13. func StructToSlice(data interface{}) []interface{} {
  14. var (
  15. reflectValue = reflect.ValueOf(data)
  16. reflectKind = reflectValue.Kind()
  17. )
  18. for reflectKind == reflect.Ptr {
  19. reflectValue = reflectValue.Elem()
  20. reflectKind = reflectValue.Kind()
  21. }
  22. switch reflectKind {
  23. case reflect.Struct:
  24. array := make([]interface{}, 0)
  25. // Note that, it uses the gconv tag name instead of the attribute name if
  26. // the gconv tag is fined in the struct attributes.
  27. for k, v := range gconv.Map(reflectValue) {
  28. array = append(array, k)
  29. array = append(array, v)
  30. }
  31. return array
  32. }
  33. return nil
  34. }