如何获取结构体的字符串表示形式?

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

How can I get the string representation of a struct?

问题

对于我的应用程序来说,字符串是否可读并不重要。

英文:

For my application, it does not matter if the string is human readable or not.

答案1

得分: 155

如果这是一个“单向”序列化(用于调试或记录日志等),那么fmt.Printf("%#v", var)非常好。 (更新:要将输出放入字符串而不是打印出来,请使用str := fmt.Sprintf("%#v", var)

如果大小很重要,可以使用%v,但我喜欢%#v,因为它还包括字段名和结构类型的名称。

第三种变体是%+v,它将包括字段名,但不包括结构类型。

它们都在fmt文档的顶部有说明。

如果您需要双向序列化JSON,Gob或XML是Go中最简单/内置的选项,请参阅encoding包

英文:

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).

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.

A third variation is %+v which will include the field names, but not the struct type.

They are all documented at the top of the fmt documentation.

If you need two-way serialization JSON, Gob or XML are the easiest/built-in options in Go, see the encoding packages.

答案2

得分: 133

使用JSON是一种将结构体编码为字符串的流行方法。

您有一些限制,例如无法获取所有信息(例如每个字段的具体类型),只能序列化导出的字段,并且无法处理递归值。但这是一种简单的标准序列化数据的方法。

工作示例:

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

给出以下输出:

{"Int":42,"String":"Hello World!","ByteSlice":"AAECAwQ="}

https://play.golang.org/p/sx-xdSxAOG

英文:

One popular way of encoding structs into strings is using 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="}

https://play.golang.org/p/sx-xdSxAOG

答案3

得分: 15

将一个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!"})
}
输出
Foo Says: Hello World!
英文:

Attaching a String() function to a named struct allows us to convert a struct to a 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!

答案4

得分: 10

你还可以添加一个具有该结构接收器的函数。

// URL:Sitemap Xml
type URL struct {
    Loc string `xml:"loc"`
}

// URLSET:Sitemap XML
type URLSET struct {
    URLS []URL `xml:"url"`
}

// 将结构转换为字符串格式。
func (u URL) String() string {
    return fmt.Sprintf(u.Loc)
}

因此,打印此结构字段将返回一个字符串。

fmt.Println(urls.URLS)
英文:

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.

fmt.Println(urls.URLS)

答案5

得分: 3

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使用json.Marshal @Matheus Santana

BenchmarkStructSprintSharp: fmt.Sprintf("%#v", &a) @Ask Bjørn Hansen

BenchmarkStructSprint: fmt.Sprintf("%v", &a)

BenchmarkStructSprintPlus: fmt.Sprintf("%+v", &a)

结果是,json.Marshal性能更好。

英文:

Using json or fmt.Sprintf, I make a benchmark,

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

BenchmarkStructSprintSharp: fmt.Sprintf("%#v", &a) @Ask Bjørn Hansen

BenchmarkStructSprint: fmt.Sprintf("%v", &a)

BenchmarkStructSprintPlus: fmt.Sprintf("%+v", &a)

The result is, json.Marshal is better performance.

huangapple
  • 本文由 发表于 2013年5月2日 13:39:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/16331063.html
匿名

发表评论

匿名网友

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

确定