我正在嘗試對包含Interface {}作為字段的結構進行解編碼。這里的問題是,編碼工作正常,但是如果我嘗試將數(shù)據(jù)解碼data為值get { <nil>},如果更改Data interface{}為Data substring,它實際上可以工作,但這對我來說不是解決方案,因為我想將查詢結果緩存到數(shù)據(jù)庫中,該數(shù)據(jù)庫的類型取決于查詢。(例如Users或Cookies)最小的工作實例來源http://play.golang.org/p/aX7MIfqrWlpackage mainimport ( "bytes" "encoding/gob" "fmt")type Data struct { Name string Data interface{}}type SubType struct { Foo string}func main() { // Encode encodeData := Data{ Name: "FooBar", Data: SubType{Foo: "Test"}, } mCache := new(bytes.Buffer) encCache := gob.NewEncoder(mCache) encCache.Encode(encodeData) fmt.Printf("Encoded: ") fmt.Println(mCache.Bytes()) // Decode var data Data pCache := bytes.NewBuffer(mCache.Bytes()) decCache := gob.NewDecoder(pCache) decCache.Decode(&data) fmt.Printf("Decoded: ") fmt.Println(data)}產(chǎn)出預期產(chǎn)量編碼:[37255129 3 1 1 4 68 97 116 97 1 255 130 0 1 2 1 4 78 97 109 101 1 12 0 1 4 68 97 116 97 1 255 132 0 0 0 0 29 255 131 3 1 1 7 83117 98 84 121 112 101 1 255 132 0 1 1 1 3 70 111 111 1 12 0 0 0 19 255 130 1 6 70 111 111 66 97 114 1 1 4 84 101 115 116 0 0]解碼:{FooBar {測試}}當前結果編碼:[37255129 3 1 1 4 68 97 116 97 1 255 130 0 1 2 1 4 78 97 109 101 1 12 0 1 4 68 97 116 97 1 255 132 0 0 0 0 29 255 131 3 1 1 7 83117 98 84 121 112 101 1 255 132 0 1 1 1 3 70 111 111 1 12 0 0 0 19 255 130 1 6 70 111 111 66 97 114 1 1 4 84 101 115 116 0 0]解碼后:{}
- 2 回答
- 0 關注
- 298 瀏覽
添加回答
舉報
0/150
提交
取消