Google app engine 使用反射将数据从序列化转换回Go结构时出现问题
在Go中使用反射将数据从缓存动态提取到各种静态声明的结构类型时遇到问题:Google app engine 使用反射将数据从序列化转换回Go结构时出现问题,google-app-engine,pointers,reflection,go,interface,Google App Engine,Pointers,Reflection,Go,Interface,在Go中使用反射将数据从缓存动态提取到各种静态声明的结构类型时遇到问题: func FetchFromCacheOrSomewhereElse(cacheKey string, returnType reflect.Type) (out interface {}, err error) { fetchFromCache := reflect.New(returnType).Interface(); _, err=memcache.Gob.Get(*context, cacheKe
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;
}
似乎reflect
不会将此静态类型的缓存数据转换回reflect值,而是返回此错误:gob:localinterface type*接口{}只能从远程接口类型解码;收到的混凝土类型
…:\
此数据保存在代码中的其他位置,并保存到缓存中,而不需要reflect
memcache.Gob.Get()
,它期望“目标”作为指针,包装到接口{}
中
您的fetchFromCache
已经是:一个指针,指向包装在接口{}
中的指定类型(returnType
)的值。因此,在将其传递到Gob.Get()
:按原样传递时,不需要获取其地址:
_, err=memcache.Gob.Get(*context, cacheKey, fetchFromCache)
试试这个:
memcache.Gob.Get(*context,cacheKey,fetchFromCache)
(注意fetchFromCache
之前没有地址&
操作符)。哇,facepalm。在你的帮助下,我花了一整天的时间在这件事上,终于能够靠自己把事情做好了。哈,谢谢。快速跟进问题:出于某种原因,在上述代码中,这并没有返回true
<代码>(err==memcache.ErrCacheMiss)。。。然而这是真实的:(err!=nil&&err.Error()==memcache.ErrCacheMiss.Error())
。。。。我更喜欢避免字符串比较,有解决方法吗?永远不要对错误进行字符串比较。我觉得你写的不太可能,请仔细检查。但要这样做:首先检查err!=零和错误!=memcache.ErrCacheMiss
如果是,请提前返回。另外,如果它是memcache.ErrCacheMiss
并且您手动成功获取数据,则应通过将err
设置为nil
来返回nil
错误。也许您的困惑是因为在本例中仍然返回memcache.ErrCacheMiss
。是的,错误不匹配但字符串匹配似乎有点奇怪。我将刷新我的pkg
目录,看看这是否有帮助。