1 回答
TA贡献1876条经验 获得超5个赞
使用反射包:
func list(ctx context.Context, kind string, dst interface{}, pageSize int, cursorStr string) string {
client, _ := datastore.NewClient(ctx, "my-proj")
query := datastore.NewQuery(kind).Limit(pageSize)
if cursorStr != "" {
cursor, err := datastore.DecodeCursor(cursorStr)
if err != nil {
log.Fatalf("Bad cursor %q: %v", cursorStr, err)
}
query = query.Start(cursor)
}
// Get reflect value for the result slice.
results := reflect.ValueOf(dst).Elem()
// Allocate new value of the slice element type.
// resultp is pointer to that value.
resultp := reflect.New(results.Type().Elem())
it := client.Run(ctx, query)
_, err := it.Next(resultp.Interface())
for err == nil {
// Append last value to results
results.Set(reflect.Append(results, resultp.Elem())
_, err = it.Next(resultp.Interface())
}
if err != iterator.Done {
log.Fatalf("Failed fetching results: %v", err)
}
// Get the cursor for the next page of results.
nextCursor, err := it.Cursor()
// [END datastore_cursor_paging]
_ = err // Check the error.
_ = nextCursor // Use nextCursor.String as the next page's token.
}
使用指向目标切片的指针调用函数:
var data []Tasks
cursor := list(ctx, "Tasks", &data, 10, "")
- 1 回答
- 0 关注
- 156 浏览
添加回答
举报