簡體   English   中英

如何對作為切片的接口{}進行子切片?

[英]How to sub slice an interface{} that is a slice?

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.

由於您是采用interface{}參數的datastore.GetMulti的調用者,因此您可以提供任何具體值作為該參數; 它不需要事先轉換為空接口類型。 換句話說,任何東西都可以實現空接口,所以只需傳遞那個東西。

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應該是一個泛型函數,同樣取一個interface{}值,那么你將不得不使用反射,如下例所示 ,而不是fmt.Println ,而你的fmt.Println長度你稱之為datastore.GetMulti與每個子datastore.GetMulti

package main

import "fmt"
import "reflect"

func GetMulti(i interface{}) {
    v := reflect.ValueOf(i)
    if v.Kind() != reflect.Slice {
        panic("argument not a slice")
    }
    l := v.Len()
    p := (l / 1000)
    for i := 0; i < p; i++ {
        fmt.Println(v.Slice(i*1000, (i+1)*1000).Len())
    }
    fmt.Println(v.Slice(p*1000, l).Len())

}

func main() {
    s := make([]int, 3560, 3560)
    GetMulti(s)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM