英文:
Golang: print struct as it would appear in source code
问题
与这个问题类似,但并不完全相同。
我正在进行一些代码生成,从Go中生成.go文件。我有一个结构体,我想生成它的文本表示,以便我可以将其作为字面量插入生成的代码中。
所以,如果我有 myVal := SomeStruct{foo : 1, bar : 2}
,我想要得到字符串 "SomeStruct{foo : 1, bar : 2}"
。
在Go中是否可能实现这个?
英文:
Similar to this question but not quite identical.
I'm doing some code-generation, making .go files from within Go. I've got a struct, and I want to generate the text representation of it so that I can insert it as a literal into the generated code.
So, if I had myVal := SomeStruct{foo : 1, bar : 2}
, I want to get the string "SomeStruct{foo : 1, bar : 2}"
.
Is this possible in Go?
答案1
得分: 18
来自fmt
包:
> %#v 值的Go语法表示
这是在删除输出中的包标识符(在此示例中为main.
)后,使用内置格式化的最接近的表示。
type T struct {
A string
B []byte
}
fmt.Printf("%#v\n", &T{A: "hello", B: []byte("world")})
// 输出
// &main.T{A:"hello", B:[]uint8{0x77, 0x6f, 0x72, 0x6c, 0x64}}
英文:
From the fmt
package:
> %#v a Go-syntax representation of the value
This is as close as you can come with built-in formatting, after removing the package identifier (main.
in this example) from the output.
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}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论