ANi*_*sus 72
将结构编码为字符串的一种流行方法是使用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))
}
Run Code Online (Sandbox Code Playgroud)
提供此输出:
{"Int":42,"String":"Hello World!","ByteSlice":"AAECAwQ="}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/sx-xdSxAOG
小智 8
您还可以使用该结构接收器添加一个函数。
// 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)
}
Run Code Online (Sandbox Code Playgroud)
所以打印这个 struct 字段将返回一个字符串。
fmt.Println(urls.URLS)
Run Code Online (Sandbox Code Playgroud)
小智 6
将 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!"})
}
Run Code Online (Sandbox Code Playgroud)
output:
Foo Says: Hello World!
Run Code Online (Sandbox Code Playgroud)