递归展开结构定义?

huangapple go评论88阅读模式
英文:

Recursively expanding struct definition?

问题

如何扩展结构定义以显示嵌套类型?例如,我想将以下代码扩展为:

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

扩展后的代码如下所示:

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

背景:逆向工程现有代码。

英文:

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

得分: 2

你可以尝试以下代码来列出结构体中定义的所有字段,并递归地列出找到的结构体。

虽然它的输出结果不完全符合你的要求,但非常接近,可能可以进行适当的调整。

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{})
}

以上代码的输出结果如下:

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

希望对你有帮助!

英文:

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.

<!-- language: go -->

package main 

import (
    &quot;reflect&quot;
    &quot;fmt&quot;
)

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 &lt; t.NumField(); i++ {
        f := t.Field(i)
        fmt.Printf(&quot;%v%v %v\n&quot;, prefix, f.Name, f.Type)
        if f.Type.Kind() == reflect.Struct {
            printFields(fmt.Sprintf(&quot;  %v&quot;, prefix), f.Type)
        }
    }    
}

func printExpandedStruct(s interface{}) {
    printFields(&quot;&quot;, 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

huangapple
  • 本文由 发表于 2017年3月16日 03:45:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/42819318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定