我有一个包含类型为
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"
}