方法如下:
// GetAll depres the cursor c to slicep where slicep is a // pointer to a slice of pointers to values.func GetAll(ctx context.Context, c *Cursor, slicep interface{}) error { // Get the slice. Call Elem() because arg is pointer to the slice. slicev := reflect.ValueOf(slicep).Elem() // Get value type. First call to Elem() gets slice // element type. Second call to Elem() dereferences // the pointer type. valuet := slicev.Type().Elem().Elem() // Iterate through the cursor... for c.Next(ctx) { // Create new value. valuep := reflect.New(valuet) // Depre to that value. if err := c.Depre(valuep.Interface()); err != nil { return err } // Append value pointer to slice. slicev.Set(reflect.Append(slicev, valuep)) } return c.Err()}这样称呼它:
var data []*Terr := GetAll(ctx, c, &data)if err != nil { // handle error}在Go Playground上运行它。
这是与非指针切片元素一起使用的代码的概括:
func GetAll(ctx context.Context, c *Cursor, slicep interface{}) error { slicev := reflect.ValueOf(slicep).Elem() valuet := slicev.Type().Elem() isPtr := valuet.Kind() == reflect.Ptr if isPtr { valuet = valuet.Elem() } for c.Next(ctx) { valuep := reflect.New(valuet) if err := c.Depre(valuep.Interface()); err != nil { return err } if !isPtr { valuep = valuep.Elem() } slicev.Set(reflect.Append(slicev, valuep)) } return c.Err()}


