无法解码gob数据

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

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"},
}

  1. m := new(bytes.Buffer)
  2. enc := gob.NewEncoder(m)
  3. enc.Encode(thing)
  4. err := ioutil.WriteFile("gob_data", m.Bytes(), 0600)
  5. if err != nil {
  6. panic(err)
  7. }
  8. fmt.Printf("刚刚保存了gob:%v\n", thing)
  9. n,err := ioutil.ReadFile("gob_data")
  10. if err != nil {
  11. fmt.Printf("无法读取文件")
  12. panic(err)
  13. }
  14. p := bytes.NewBuffer(n)
  15. dec := gob.NewDecoder(p)
  16. e := []hashinfo{}
  17. err = dec.Decode(&e)
  18. if err != nil {
  19. fmt.Printf("无法解码")
  20. panic(err)
  21. }
  22. 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

  1. import (
  2. "fmt"
  3. "encoding/gob"
  4. "bytes"
  5. "io/ioutil"
  6. )
  7. type hashinfo struct {
  8. fname string
  9. hash string
  10. }
  11. func main() {
  12. thing := []hashinfo{
  13. {"rahul","test"},
  14. {"boya","test2"},
  15. }
  16. m := new(bytes.Buffer)
  17. enc := gob.NewEncoder(m)
  18. enc.Encode(thing)
  19. err := ioutil.WriteFile("gob_data", m.Bytes(), 0600)
  20. if err != nil {
  21. panic(err)
  22. }
  23. fmt.Printf("just saved gob with %v\n", thing)
  24. n,err := ioutil.ReadFile("gob_data")
  25. if err != nil {
  26. fmt.Printf("cannot read file")
  27. panic(err)
  28. }
  29. p := bytes.NewBuffer(n)
  30. dec := gob.NewDecoder(p)
  31. e := []hashinfo{}
  32. err = dec.Decode(&e)
  33. if err != nil {
  34. fmt.Printf("cannot decode")
  35. panic(err)
  36. }
  37. fmt.Printf("just read gob from file and it's showing: %v\n", e)
  38. }

I have created e := []hashinfo{} object in order to decode gobject. Am I doing something wrong there ?

答案1

得分: 3

您的type hashinfo中的字段未导出,无法进行反序列化。请尝试使用FnameHash

英文:

Your fields in type hashinfo are not exported and cannot be deserialized. Try with Fname and Hash.

huangapple
  • 本文由 发表于 2013年11月26日 05:03:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/20203257.html
匿名

发表评论

匿名网友

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

确定