12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package lmaxapi
- import "reflect"
- import "fmt"
- type structItem struct {
- Offset int
- Align int
- Size int
- Name string
- Value interface{}
- }
- func structKV(i interface{}, recursion bool) ([]structItem, error) {
- values := reflect.ValueOf(i)
- if values.Kind() == reflect.Ptr {
- return structKV(values.Elem().Interface(), recursion)
- }
- if values.Kind() != reflect.Struct {
- return nil, fmt.Errorf("StructKeyValues: in params not a struct")
- }
- types := reflect.TypeOf(i)
- num := types.NumField()
- elms := make([]structItem, 0)
- for i := 0; i < num; i++ {
- elm := values.Field(i)
- if elm.CanInterface() {
- if recursion && elm.Kind() == reflect.Struct {
- v, err := structKV(elm.Interface(), recursion)
- if err == nil && len(v) > 0 {
- elms = append(elms, v...)
- }
- continue
- }
- field := types.Field(i)
- item := structItem{}
- item.Offset = int(field.Offset)
- item.Align = int(field.Type.Align())
- item.Size = int(field.Type.Size())
- item.Name = field.Name
- item.Value = elm.Interface()
- elms = append(elms, item)
- }
- }
- return elms, nil
- }
- func PrintStruct(item interface{}) {
- data, err := structKV(item, true)
- if err != nil {
- panic(err)
- }
- types := reflect.TypeOf(item)
- fmt.Println("name:", types.Name(), "total:", types.Size())
- for i := 0; i < len(data); i++ {
- fmt.Println(data[i])
- }
- }
|