2016-12-05 35 views
2

this question类似,但不完全相同。Golang:打印出现在源代码中的结构

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

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

Go可能吗?

回答

5

fmt包:

%#v a Go-syntax representation of the value 

这是因为接近你可以配备内置格式化,从输出中去除包标识符(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

+0

我想这一点,但是当我有'Foo类型string'和'{场:美孚( “酒吧”)}',它只是打印这'{场“酒吧“}'。任何解决方法? – jmite

+0

@jmite:struct中的field是什么类型的? – JimB

+0

它的类型'Foo' – jmite