无法解码gob数据

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

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中的字段未导出,无法进行反序列化。请尝试使用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:

确定