Issue translating data back from serialization into Go struct dynamically using reflection

早过忘川 提交于 2019-12-11 05:55:59

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/37504458/issue-translating-data-back-from-serialization-into-go-struct-dynamically-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!