问题描述
我关注了 https://blog.golang.org/gob 链接。并写了一个示例,其中结构包含所有字符串数据。 这是我的示例:
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
)
type P struct {
X string
a string
Name string
}
type Q struct {
X string
a string
Name string
}
func main() {
// Initialize the encoder and decoder. normally enc and dec would be
// bound to network connections and the encoder and decoder would
// run in different processes.
var network bytes.Buffer // Stand-in for a network connection
enc := gob.NewEncoder(&network) // Will write to network.
dec := gob.NewDecoder(&network) // Will read from network.
// Encode (send) the value.
err := enc.Encode(P{"My string","Pythagoras","a string"})
if err != nil {
log.Fatal("encode error:",err)
}
// Decode (receive) the value.
var q Q
err = dec.Decode(&q)
if err != nil {
log.Fatal("decode error:",err)
}
fmt.Println(q.X,q.Name)
fmt.Println(q.a)
}
玩golang:https://play.golang.org/p/3aj0hBG7wMj
预期输出:
My string a string
Pythagoras
实际输出
My string a string
我不知道为什么输出中缺少“pythagoras”字符串。当我在结构中有多个字符串、整数数据并使用 gob 进行处理时,我观察到了类似的行为。
如何处理字符串? 我的程序有什么问题?
解决方法
gob 编解码器忽略 unexported 字段。通过将字段名称中的第一个字母大写导出字段:
type P struct {
X string
A string
Name string
}
对类型 Q
进行类似的更改。
您的 a
字段未导出(名称以小写字母开头)。 Go 的反射以及 JSON、YAML 和 gob 等扩展编组器无法访问未导出的结构字段,只能访问导出的字段。
您为名称分配值 "Pythagoras"
的字段必须导出。
type P struct {
X string
a string // --> change name to A
Name string
}
type Q struct {
X string
a string // --> change name to A
Name string
}
在您链接的博客文章中,有记录(Ctrl+F 表示“导出”):
仅对导出的字段进行编码和解码。
,将结构 a
和 P
中的 Q
字段设为公开。然后将其编码和解码。
type P struct {
X string
A string
Name string
}
type Q struct {
X string
A string
Name string
}