printStruct.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package lmaxapi
  2. import "reflect"
  3. import "fmt"
  4. type structItem struct {
  5. Offset int
  6. Align int
  7. Size int
  8. Name string
  9. Value interface{}
  10. }
  11. func structKV(i interface{}, recursion bool) ([]structItem, error) {
  12. values := reflect.ValueOf(i)
  13. if values.Kind() == reflect.Ptr {
  14. return structKV(values.Elem().Interface(), recursion)
  15. }
  16. if values.Kind() != reflect.Struct {
  17. return nil, fmt.Errorf("StructKeyValues: in params not a struct")
  18. }
  19. types := reflect.TypeOf(i)
  20. num := types.NumField()
  21. elms := make([]structItem, 0)
  22. for i := 0; i < num; i++ {
  23. elm := values.Field(i)
  24. if elm.CanInterface() {
  25. if recursion && elm.Kind() == reflect.Struct {
  26. v, err := structKV(elm.Interface(), recursion)
  27. if err == nil && len(v) > 0 {
  28. elms = append(elms, v...)
  29. }
  30. continue
  31. }
  32. field := types.Field(i)
  33. item := structItem{}
  34. item.Offset = int(field.Offset)
  35. item.Align = int(field.Type.Align())
  36. item.Size = int(field.Type.Size())
  37. item.Name = field.Name
  38. item.Value = elm.Interface()
  39. elms = append(elms, item)
  40. }
  41. }
  42. return elms, nil
  43. }
  44. func PrintStruct(item interface{}) {
  45. data, err := structKV(item, true)
  46. if err != nil {
  47. panic(err)
  48. }
  49. types := reflect.TypeOf(item)
  50. fmt.Println("name:", types.Name(), "total:", types.Size())
  51. for i := 0; i < len(data); i++ {
  52. fmt.Println(data[i])
  53. }
  54. }