从 Go 中的实例打印结构定义

我正在寻找一个 lib 或片段,它允许(漂亮地)打印结构实例的内容而不是它的结构。下面是一些代码和预期的输出:


package main


import "fantastic/structpp"


type Foo struct {

    Bar string

    Other int

}


func main() {

    i := Foo{Bar: "This", Other: 1}

    str := structpp.Sprint{i}

    fmt.Println(str)

}

会打印(这个或类似的):


Foo struct {

    Bar string

    Other int

}   

请注意,我知道github.com/davecgh/go-spew/spew但我不想漂亮地打印数据,我只需要结构的定义。


手掌心
浏览 107回答 2
2回答

摇曳的蔷薇

这样的事情行得通吗?可能需要根据您的特定结构和用例进行一些调整(是否要打印接口{},其中值实际上是一个结构等)package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "reflect")func printStruct(t interface{}, prefix string) {&nbsp; &nbsp; s := reflect.Indirect(reflect.ValueOf(t))&nbsp; &nbsp; typeOfT := s.Type()&nbsp; &nbsp; for i := 0; i < s.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; f := s.Field(i)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s%s %s\n", prefix, typeOfT.Field(i).Name, typeOfT.Field(i).Type)&nbsp; &nbsp; &nbsp; &nbsp; switch f.Type().Kind() {&nbsp; &nbsp; &nbsp; &nbsp; case reflect.Struct, reflect.Ptr:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s{\n", prefix)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printStruct(f.Interface(), prefix+"\t")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s}\n", prefix)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后,对于这个结构:type C struct {&nbsp; &nbsp; D string}type T struct {&nbsp; &nbsp; A int&nbsp; &nbsp; B string&nbsp; &nbsp; C *C&nbsp; &nbsp; E interface{}&nbsp; &nbsp; F map[string]int}t := T{&nbsp; &nbsp; A: 23,&nbsp; &nbsp; B: "hello_world",&nbsp; &nbsp; C: &C{&nbsp; &nbsp; &nbsp; &nbsp; D: "pointer",&nbsp; &nbsp; },&nbsp; &nbsp; E: &C{&nbsp; &nbsp; &nbsp; &nbsp; D: "interface",&nbsp; &nbsp; },}你得到:A intB stringC *main.C{&nbsp; &nbsp; D string}E interface {}F map[string]intGo Playground 链接:https://play.golang.org/p/IN8-fCOe0OS

杨魅力

除了使用反射,我看不到其他选择func Sprint(v interface{}) string {&nbsp; &nbsp; t := reflect.Indirect(reflect.ValueOf(v)).Type()&nbsp; &nbsp; fieldFmt := ""&nbsp; &nbsp; for i := 0; i < t.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; field := t.Field(i)&nbsp; &nbsp; &nbsp; &nbsp; fieldFmt += "\t" + field.Name + " " + field.Type.Name() + "\n"&nbsp; &nbsp; }&nbsp; &nbsp; return "type " + t.Name() + " struct {\n" + fieldFmt + "}"}请注意,尽管此函数没有验证/检查,并且可能会对非结构输入造成恐慌。编辑:去游乐场:https://play.golang.org/p/5RiAt86Wj9F哪些输出:type Foo struct {&nbsp; &nbsp; Bar string&nbsp; &nbsp; Other int}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go