Search code examples
goreverse-engineering

Recursively expanding struct definition?


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.


Solution

  • 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