英文:
Unable to decode gob data
问题
我有一个简单的结构体类型需要进行编码。然而,在解码数据时,我做了一些基本错误。每次尝试解码时,我都会遇到EOF恐慌错误。
// 将一个映射编码为gob。将gob保存到磁盘。从磁盘读取gob。将gob解码为另一个映射。
package main
import (
"fmt"
"encoding/gob"
"bytes"
"io/ioutil"
)
type hashinfo struct {
fname string
hash string
}
func main() {
thing := []hashinfo{
{"rahul","test"},
{"boya","test2"},
}
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
enc.Encode(thing)
err := ioutil.WriteFile("gob_data", m.Bytes(), 0600)
if err != nil {
panic(err)
}
fmt.Printf("刚刚保存了gob:%v\n", thing)
n,err := ioutil.ReadFile("gob_data")
if err != nil {
fmt.Printf("无法读取文件")
panic(err)
}
p := bytes.NewBuffer(n)
dec := gob.NewDecoder(p)
e := []hashinfo{}
err = dec.Decode(&e)
if err != nil {
fmt.Printf("无法解码")
panic(err)
}
fmt.Printf("刚刚从文件中读取了gob,并显示为:%v\n", e)
}
为了解码gob对象,我创建了e := []hashinfo{}对象。在那里我做错了什么吗?
英文:
I have a simple struct type which I am encoding. However, I am doing something fundamentally wrong while decoding the data. Every time I try to decode it, I get EOF panic error.
//Encoding a map to a gob. Save the gob to disk. Read the gob from disk. Decode the gob into another map.
package main
import (
"fmt"
"encoding/gob"
"bytes"
"io/ioutil"
)
type hashinfo struct {
fname string
hash string
}
func main() {
thing := []hashinfo{
{"rahul","test"},
{"boya","test2"},
}
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
enc.Encode(thing)
err := ioutil.WriteFile("gob_data", m.Bytes(), 0600)
if err != nil {
panic(err)
}
fmt.Printf("just saved gob with %v\n", thing)
n,err := ioutil.ReadFile("gob_data")
if err != nil {
fmt.Printf("cannot read file")
panic(err)
}
p := bytes.NewBuffer(n)
dec := gob.NewDecoder(p)
e := []hashinfo{}
err = dec.Decode(&e)
if err != nil {
fmt.Printf("cannot decode")
panic(err)
}
fmt.Printf("just read gob from file and it's showing: %v\n", e)
}
I have created e := []hashinfo{} object in order to decode gobject. Am I doing something wrong there ?
答案1
得分: 3
您的type hashinfo
中的字段未导出,无法进行反序列化。请尝试使用Fname
和Hash
。
英文:
Your fields in type hashinfo
are not exported and cannot be deserialized. Try with Fname
and Hash
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论