如何对作为切片的接口{}进行子切片?

时间:2014-04-04 09:59:21

标签: google-app-engine go

datastore.GetMulti(c appengine.Context, key []*Key, dst interface{}) API允许我最多获得1000个实体。我想得到更多。

一般来说,解决这个问题的一个明显方法是创建一个包装函数mypkg.GetMulti(),它对原始参数进行子切片(key[0:1000], key[1000:2000]...),并用它们多次调用datastore.GetMulti()

非常清楚如何分片key []*Key,但如何分片dst interface{}可能是:

// dst must be a []S, []*S, []I or []P, for some struct type S, some interface
// type I, or some non-interface non-pointer type P such that P or *P
// implements PropertyLoadSaver. If an []I, each element must be a valid dst
// for Get: it must be a struct pointer or implement PropertyLoadSaver.
//
// As a special case, PropertyList is an invalid type for dst, even though a
// PropertyList is a slice of structs. It is treated as invalid to avoid being
// mistakenly passed when []PropertyList was intended.

1 个答案:

答案 0 :(得分:2)

由于您是datastore.GetMulti的调用方,它接受interface{}参数,因此您可以提供任何具体值作为该参数;它不需要事先转换为空接口类型。换句话说,任何东西都可以实现空接口,所以只需传递那个东西。

func GetMulti() {
    mySlice := make([]Whatever, 3000, 3000)
    for i := 0; i < 3; i++ {
        subSlice := mySlice[i * 1000 : (i + 1) * 1000]
        datastore.GetMulti(c,k, subSlice) // 'c' and 'k' assumed to be defined
    }
}

如果mypkg.GetMulti应该是通用函数,同时采用{​​{1}}值,那么您将必须使用反射,如下面的example而不是{{1使用每个子切片调用interface{}的子切片的长度:

fmt.Println