亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Gob解碼和編碼接口{}

使用Gob解碼和編碼接口{}

Go
牛魔王的故事 2021-05-18 17:20:31
我正在嘗試對包含Interface {}作為字段的結構進行解編碼。這里的問題是,編碼工作正常,但是如果我嘗試將數據解碼data為值get { <nil>},如果更改Data interface{}為Data substring,它實際上可以工作,但這對我來說不是解決方案,因為我想將查詢結果緩存到數據庫中,該數據庫的類型取決于查詢。(例如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)}產出預期產量編碼:[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 回答

  • 2 回答
  • 0 關注
  • 306 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號