英文:
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 (
"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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论