gpt4 book ai didi

serialization - 戈朗 : print struct as it would appear in source code

转载 作者:IT王子 更新时间:2023-10-29 01:51:01 25 4
gpt4 key购买 nike

类似于this question但不完全相同。

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

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

这在 Go 中可能吗?

最佳答案

来自 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

关于serialization - 戈朗 : print struct as it would appear in source code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com