我有这个类型的结构体interface{}
。在使用memcached(https://github.com/bradfitz/gomemcache)对其进行缓存的过程中,该结构被编组为JSON,然后从缓存中检索后将其解组回该结构。结果interface{}
字段将不可避免地指向类型为map [string] interface {}的对象(例如,该interface{}
字段只能以断言为map [string] interface {}的类型),编组和解组过程未保留类型信息。是否有任何方法可以在编组过程中保存此信息,从而可以正确地将其编组?还是我必须使用其他编解码器或其他工具?
type A struct {
value interface{}
}
type B struct {
name string
id string
}
func main() {
a := A{value: B{name: "hi", id: "12345"}}
cache.Set("a", a) // Marshals 'a' into JSON and stores in cache
result = cache.Get("a") // Retrieves 'a' from cache and unmarshals
fmt.Printf("%s", result.value.(B).name) // Generates error saying that
// map[string]interface{} cannot be type asserted as a 'B' struct
fmt.Printf("%s", result.value.(map[string]interface{})["name"].(string)) // Correctly prints "12345"
}
简短版,不,您不能那样做,但是您几乎没有选择。
A.Value
使用B
代替interface{}
。A
该转换A.Value
从地图到B
,如果它是不是已经B
。encoding/gob
字节并将其存储在memcache中,然后使用像这样的函数将其转换回去NewA(b []byte) *A
。对于using gob
,必须在编码/解码之前先向每个结构注册,例如:
func init() {
//where you should register your types, just once
gob.Register(A{})
gob.Register(B{})
}
func main() {
var (
buf bytes.Buffer
enc = gob.NewEncoder(&buf)
dec = gob.NewDecoder(&buf)
val = A{B{"name", "id"}}
r A
)
fmt.Println(enc.Encode(&val))
fmt.Println(dec.Decode(&r))
fmt.Printf("%#v", r)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句