Golang:在源代码中出现的print结构

jmi*_*ite 1 serialization struct code-generation pretty-print go

此问题类似但不完全相同.

我正在做一些代码生成,从Go中制作.go文件.我有一个结构,我想生成它的文本表示,以便我可以将它作为文字插入到生成的代码中.

所以,如果我有 myVal := SomeStruct{foo : 1, bar : 2},我想得到字符串"SomeStruct{foo : 1, bar : 2}".

Go有可能吗?

Jim*_*imB 6

fmt包装:

%#v   a Go-syntax representation of the value
Run Code Online (Sandbox Code Playgroud)

main.在从输出中删除包标识符(在此示例中)之后,这与内置格式一样接近.

type T struct {
    A string
    B []byte
}

fmt.Printf("%#v\n", &T{A: "hello", B: []byte("world")})

// out
// &main.T{A:"hello", B:[]uint8{0x77, 0x6f, 0x72, 0x6c, 0x64}}
Run Code Online (Sandbox Code Playgroud)