2013-11-25 27 views
-1

我有一個簡單的結構類型,我正在編碼。但是,在解碼數據時,我正在做一些根本性錯誤。每次我嘗試解碼它時,都會收到EOF恐慌錯誤。無法解碼採樣數據

//將地圖編碼爲玻璃塊。將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。我在那裏做錯了什麼?

回答

3

您在type hashinfo中的字段未導出,無法反序列化。試用FnameHash

+0

哦。順便說一句,最新的處理變量與大寫內部結構。 – Rahul

+1

它們被導出(在包裹外可見)。通過Go遊覽工作,閱讀Effective Go並查看規範。 – Volker