string 在 Go 中,如何获取结构的字符串表示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16331063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Go, how can I get the string representation of a struct?
提问by abw333
For my application, it does not matter if the string is human readable or not.
对于我的应用程序,字符串是否是人类可读的并不重要。
回答by Ask Bj?rn Hansen
If it's a "one way" serialization (for debugging or logging or whatever) then fmt.Printf("%#v", var)
is very nice. (Update: to put the output into a string instead of printing it, use str := fmt.Sprintf("%#v", var)
.
如果它是“单向”序列化(用于调试或日志记录或其他),那么fmt.Printf("%#v", var)
非常好。(更新:要将输出放入字符串而不是打印它,请使用str := fmt.Sprintf("%#v", var)
.
If size matters you can use %v
, but I like %#v
because it will also include the field names and the name of the struct type.
如果大小很重要,您可以使用%v
,但我喜欢,%#v
因为它还将包括字段名称和结构类型的名称。
A third variation is %+v
which will include the field names, but not the struct type.
第三种变体%+v
将包括字段名称,但不包括结构类型。
They are all documented at the top of the fmt documentation.
它们都记录在fmt 文档的顶部。
If you need two-way serialization JSON, Gob or XML are the easiest/built-in options in Go, see the encoding packages.
如果您需要双向序列化 JSON,Gob 或 XML 是 Go 中最简单/内置的选项,请参阅编码包。
回答by ANisus
One popular way of encoding structs into strings is using JSON.
将结构编码为字符串的一种流行方法是使用JSON。
You have certain limitations such as not getting all the information (such as the specific type of each field), only serializing exported fields, and not handling recursive values. But it is a simple standard way of serializing data.
您有某些限制,例如无法获取所有信息(例如每个字段的特定类型)、仅序列化导出的字段以及不处理递归值。但它是序列化数据的简单标准方式。
Working example:
工作示例:
package main
import (
"fmt"
"encoding/json"
)
type s struct {
Int int
String string
ByteSlice []byte
}
func main() {
a := &s{42, "Hello World!", []byte{0,1,2,3,4}}
out, err := json.Marshal(a)
if err != nil {
panic (err)
}
fmt.Println(string(out))
}
Give this output:
给出这个输出:
{"Int":42,"String":"Hello World!","ByteSlice":"AAECAwQ="}
回答by Santosh Pillai
you can also add a function with that struct receiver.
您还可以使用该结构接收器添加一个函数。
// URL : Sitemap Xml
type URL struct {
Loc string `xml:"loc"`
}
// URLSET : Sitemap XML
type URLSET struct {
URLS []URL `xml:"url"`
}
// converting the struct to String format.
func (u URL) String() string {
return fmt.Sprintf(u.Loc)
}
So printing this struct field will return a string.
所以打印这个 struct 字段将返回一个字符串。
fmt.Println(urls.URLS)
回答by Arghyadeb
Attaching a String() function to a named struct allows us to convert a struct to a string.
将 String() 函数附加到命名结构允许我们将结构转换为字符串。
package main
import "fmt"
type foo struct {
bar string
}
func (f foo) String() string {
return fmt.Sprintf("Foo Says: %s", f.bar)
}
func main() {
fmt.Println(foo{"Hello World!"})
}
output:
Foo Says: Hello World!
回答by xu feng
Using json
or fmt.Sprintf
, I make a benchmark,
使用json
or fmt.Sprintf
,我做一个基准,
BenchmarkStructJson-8 1000000 1773 ns/op
BenchmarkStructSprintSharp-8 200000 6139 ns/op
BenchmarkStructSprint-8 500000 2763 ns/op
BenchmarkStructSprintPlus-8 300000 4373 ns/op
BenchmarkStructJson
is using json.Marshal
@Matheus Santana
BenchmarkStructJson
正在使用json.Marshal
@Matheus Santana
BenchmarkStructSprintSharp
: `fmt.Sprintf("%#v", &a) @Ask Bj?rn Hansen
BenchmarkStructSprintSharp
: `fmt.Sprintf("%#v", &a) @Ask Bj?rn Hansen
BenchmarkStructSprint
: `fmt.Sprintf("%v", &a)
BenchmarkStructSprint
: `fmt.Sprintf("%v", &a)
BenchmarkStructSprintPlus
: `fmt.Sprintf("%+v", &a)
BenchmarkStructSprintPlus
: `fmt.Sprintf("%+v", &a)
The result is, json.Marshal
is better performance.
结果是,json.Marshal
性能更好。