猿问

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

该datastore.GetMulti(c appengine.Context, key []*Key, dst interface{})API可以让我得到最多1000元。我想得到更多。


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


很清楚如何 sub slice 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.


慕容3067478
浏览 167回答 1
1回答

拉风的咖菲猫

由于您是datastore.GetMulti接受interface{}参数的调用者,因此您可以提供任何具体值作为该参数;它不需要事先转换为空接口类型。换句话说,任何东西都实现了空接口,所以只需传递那个东西。func GetMulti() {&nbsp; &nbsp; mySlice := make([]Whatever, 3000, 3000)&nbsp; &nbsp; for i := 0; i < 3; i++ {&nbsp; &nbsp; &nbsp; &nbsp; subSlice := mySlice[i * 1000 : (i + 1) * 1000]&nbsp; &nbsp; &nbsp; &nbsp; datastore.GetMulti(c,k, subSlice) // 'c' and 'k' assumed to be defined&nbsp; &nbsp; }}如果mypkg.GetMulti应该是一个通用函数,也取一个interface{}值,那么您必须使用反射,如下例所示,而不是使用每个子切片fmt.Println调用的子切片长度datastore.GetMulti:package mainimport "fmt"import "reflect"func GetMulti(i interface{}) {&nbsp; &nbsp; v := reflect.ValueOf(i)&nbsp; &nbsp; if v.Kind() != reflect.Slice {&nbsp; &nbsp; &nbsp; &nbsp; panic("argument not a slice")&nbsp; &nbsp; }&nbsp; &nbsp; l := v.Len()&nbsp; &nbsp; p := (l / 1000)&nbsp; &nbsp; for i := 0; i < p; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(v.Slice(i*1000, (i+1)*1000).Len())&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(v.Slice(p*1000, l).Len())}func main() {&nbsp; &nbsp; s := make([]int, 3560, 3560)&nbsp; &nbsp; GetMulti(s)}
随时随地看视频慕课网APP

相关分类

Go
我要回答