将 reflect.Value 传递给 Google App Engine 中的 datastore.GetMulti。

huangapple go评论92阅读模式
英文:

Passing reflect.Value to datastore.GetMulti in Google App Engine

问题

我有一个围绕着datastore.GetMulti的包装函数mypkg.GetStart。包装函数的参数必须与appengine.GetMulti完全相同。为了举例,我想要获取dst的前两个实体。我的代码目前如下所示,但无法正常工作。datastore.GetMulti产生了错误datastore: dst has invalid type

type myEntity struct {
    Val int
}

keys := []*datastore.Key{keyOne, keyTwo, keyThree}
entities := make([]myEntity, 3)
mypkg.GetStart(c, keys, entities)

我的mypkg.GetStart代码如下:

func GetStart(c appengine.Context, keys []*datastore.Key, dst interface{}) error {
    v := reflect.ValueOf(dst)
    dstSlice := v.Slice(0, 2)
    return datastore.GetMulti(c, keys, dstSlice)
}

我该如何使其正常工作?请注意,这是对https://stackoverflow.com/questions/22859547/how-to-sub-slice-an-interface-that-is-a-slice的后续问题。

英文:

I have a wrapper function mypkg.GetStart around datastore.GetMulti. The arguments of the wrapper function must be identical to appengine.GetMulti. I would like to get the first two entities of dst, for the sake of this example. My code currently looks like below but does not work. datastore.GetMulti produces the error datastore: dst has invalid type.

type myEntity struct {
    Val Int
}

keys := []*datastore.Key{keyOne, keyTwo, keyThree}
entities := make([]myEntity, 3)
mypkg.GetStart(c, keys, enities)

My mypkg.GetStart code is as follows:

func GetStart(c appengine.Context, keys []*datastore.Key, dst interface{}) error{
    v := reflect.ValueOf(dst)
    dstSlice := v.Slice(0, 2)
    return datastore.GetMulti(c, keys, dstSlice)
}

How can I make this work? Note this is a follow up question to https://stackoverflow.com/questions/22859547/how-to-sub-slice-an-interface-that-is-a-slice

答案1

得分: 0

我通过在dstSlice中添加Interface()来使其工作:

func GetStart(c appengine.Context, keys []*datastore.Key, dst interface{}) error{
    v := reflect.ValueOf(dst)
    dstSlice := v.Slice(0, 2)
    return datastore.GetMulti(c, keys, dstSlice.Interface())
}
英文:

I got this to work by adding Interface() to dstSlice:

func GetStart(c appengine.Context, keys []*datastore.Key, dst interface{}) error{
    v := reflect.ValueOf(dst)
    dstSlice := v.Slice(0, 2)
    return datastore.GetMulti(c, keys, dstSlice.Interface())
}

huangapple
  • 本文由 发表于 2014年4月6日 02:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/22885336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定