递归扩展结构定义?

编程入门 行业动态 更新时间:2024-10-27 08:25:00
本文介绍了递归扩展结构定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

递归扩展结构定义?

本文发布于:2023-11-05 18:53:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561590.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   定义   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!