我有一个正在编码的简单结构类型。但是,我在解码数据时做了一些根本错误的事情。每次我尝试解码它时,我都会收到 EOF 恐慌错误。
//将地图编码为gob。将 gob 保存到磁盘。从磁盘读取 gob。将 gob 解码为另一张地图。包主
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)
}
我创建了 e := []hashinfo{} 对象以解码 gobject。我在那里做错了吗?
开心每一天1111
相关分类