递归扩展结构定义? [英] Recursively expanding struct definition?

查看:57
本文介绍了递归扩展结构定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何扩展结构定义以显示嵌套类型?例如,我想扩展它

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
}

类似这样:

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

上下文:对现有代码进行逆向工程.

context: reverse engineering existing code.

推荐答案

您可以尝试以下方法来列出结构中定义的所有字段,并递归列出以这种方式找到的结构.

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

这篇关于递归扩展结构定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆