Recursively expanding struct definition?

吃可爱长大的小学妹 提交于 2019-12-11 03:41:49

问题


How can expand a structure definition to show nested types? For example, I would like to expand this

type Foo struct {
  x int
  y []string
  z Bar
}
type Bar struct {
  a int
  b string
}

to something like this:

type Foo struct {
  x int
  y []string
  z Bar
    struct {
      a int
      b string
    }
}

context: reverse engineering existing code.


回答1:


You can try something along these lines to list all fields defined in a struct, recursively listing structs found in the way.

It does not produce exactly the output you asked for but it's pretty close and can probably be adapted to do so.

package main 

import (
    "reflect"
    "fmt"
)

type Foo struct {
  x int
  y []string
  z Bar
}
type Bar struct {
  a int
  b string
}

func printFields(prefix string, t reflect.Type) {
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        fmt.Printf("%v%v %v\n", prefix, f.Name, f.Type)
        if f.Type.Kind() == reflect.Struct {
            printFields(fmt.Sprintf("  %v", prefix), f.Type)
        }
    }    
}

func printExpandedStruct(s interface{}) {
    printFields("", reflect.ValueOf(s).Type())
}

func main() {
    printExpandedStruct(Foo{})
}

I get this output as a result of the above:

x int
y []string
z main.Bar
  a int
  b string


来源:https://stackoverflow.com/questions/42819318/recursively-expanding-struct-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!