doutaoer3148 2017-03-15 19:45
浏览 58
已采纳

递归扩展结构定义?

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条回答 默认 最新

  • douchen7555 2017-03-16 03:36
    关注

    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
    ", 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信