Golang:按源代码中的格式打印结构体。

huangapple go评论85阅读模式
英文:

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}}

Run

huangapple
  • 本文由 发表于 2016年12月6日 01:25:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/40979903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定