使用反射动态地将数据从序列化转换回Go结构 [英] Issue translating data back from serialization into Go struct dynamically using reflection

查看:316
本文介绍了使用反射动态地将数据从序列化转换回Go结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 我在Go中使用反射动态地将缓存中的数据动态地读取到各种静态声明的结构类型中, func FetchFromCacheOrSomewhereElse(cacheKey string,returnType reflect.Type)(out interface {},err error){
fetchFromCache:= reflect.New(returnType).Interface();
_,err = memcache.Gob.Get(* context,cacheKey,& fetchFromCache);

if(err == nil){
out = reflect.ValueOf(fetchFromCache).Elem()。Interface();

} else if(err == memcache.ErrCacheMiss){
/ *手动提取数据... * /

}

退出,犯错;

$ b $ / code>

似乎反映 code>不会将这个静态类型的缓存数据转换回反射值,而是返回这个错误: gob:local interface type * interface {}只能从远程接口类型解码;收到具体类型 ...:\



这些数据保存在缓存的其他地方,而不需要

解决方案

memcache.Gob.Get / code>这是 Codec.Get () 需要将target作为指针,将其封装到 interface {} 中。



您的 fetchFromCache 已经是这样了:指向指定类型的值的指针( returnType )包装在界面{} 中。所以你不需要把它的地址传递给 Gob.Get():按原样传递:

  _,err = memcache.Gob.Get(* context,cacheKey,fetchFromCache)


I'm having trouble using reflection in Go to fetch data from a cache dynamically into various statically declared struct types:

func FetchFromCacheOrSomewhereElse(cacheKey string, returnType reflect.Type) (out interface {}, err error) {
    fetchFromCache := reflect.New(returnType).Interface();
    _, err=memcache.Gob.Get(*context, cacheKey, &fetchFromCache);

    if (err==nil) {
        out=reflect.ValueOf(fetchFromCache).Elem().Interface();

    } else if (err==memcache.ErrCacheMiss) {
        /* Fetch data manually... */

    }

    return out, err;

}

It seems that reflect won't translate this statically typed cache data back into a reflect value, and returns this error instead: gob: local interface type *interface {} can only be decoded from remote interface type; received concrete type ... :\

This data is saved elsewhere in the code to the cache without the need for reflect.

解决方案

memcache.Gob.Get() which is Codec.Get() expects the "target" as a pointer, wrapped into an interface{}.

Your fetchFromCache is already just that: a pointer to a value of the specified type (returnType) wrapped in an interface{}. So you don't need to take its address when passing it to Gob.Get(): pass it as-is:

_, err=memcache.Gob.Get(*context, cacheKey, fetchFromCache)

这篇关于使用反射动态地将数据从序列化转换回Go结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆