我正在try 对一个包含Interface{}As字段的 struct 进行解码和编码.
问题是,编码工作得很好,但如果我try 将数据解码为data
,则值会变为{ <nil>}
.
如果我将Data interface{}
更改为Data substring
,它实际上是有效的,但这对我来说不是一个解决方案,因为我想将查询结果缓存到一个数据库,该数据库的类型取决于查询的不同.(例如Users
或Cookies
)
Minimal working example
来源
http://play.golang.org/p/aX7MIfqrWl个
package main
import (
"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)
}
输出
预期yields
编码:[37 255 129 3 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 29 255 131 3 1 1 7 83 117 98 84 121 101 1 255 132 0 1 1 1 3 70 111 1 12 0 0 0 19 255 130 1 6 70 111 66 97 114 1 4 101 116 0]
解码:{FooBar{Test}}
当前结果
编码:[37 255 129 3 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 29 255 131 3 1 1 7 83 117 98 84 121 101 1 255 132 0 1 1 1 3 70 111 1 12 0 0 0 19 255 130 1 6 70 111 66 97 114 1 4 101 116 0]
已解码:{}