【发布时间】:2019-07-14 01:31:26
【问题描述】:
我正在尝试编写一些通用方法(CRUD 方法)以在我的服务之间共享它。以下示例是一个 GetAll() 方法,它返回我的集合中存在的所有文档:
func GetAll(out interface{}) error {
// mongodb operations
// iterate through all documents
for cursor.Next(ctx) {
var item interface{}
// decode the document
if err := cursor.Decode(&item); err != nil {
return err
}
(*out) = append((*out), item)
// arrays.AppendToArray(out, item) // Read below :)
}
return nil // if no error
}
我也尝试了一些反思,但后来:
package arrays
import "reflect"
func AppendToArray(slicePtrInterface interface{}, item interface{}) {
// enter `reflect`-land
slicePtrValue := reflect.ValueOf(slicePtrInterface)
// get the type
slicePtrType := slicePtrValue.Type()
// navigate from `*[]T` to `T`
_ = slicePtrType.Elem().Elem() // crashes if input type not `*[]T`
// we'll need this to Append() to
sliceValue := reflect.Indirect(slicePtrValue)
// append requested number of zeroes
sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(item)))
}
恐慌:reflect.Set:类型primitive.D的值不可分配给类型*mongodb.Test [恢复] 恐慌:reflect.Set:类型primitive.D的值不可分配给类型*mongodb.Test
我想要的是获得与cursor.Decode(&item) 相同的方法(你可以在上面看到)
【问题讨论】:
标签: go