Why is this happening? Because one of my argument must be a slice address.
Maybe I did not made it clear for everyone.
collection.Find(bson.M{}).All(&result)
The above code is why I need a slice address.
the result variable here is what I need. Now usually I can do this
result := make([]SomeStruct, 10, 10)
But now the SomeStruct is dynamic and I need to create the slice by using reflect.MakeSlice, So
result := reflect.MakeSlice(reflect.SliceOf(SomeType))
And it errors on : result must be a slice address.
How to get a pointer to a slice using reflection
reflect.New()
my := &My{}
// Create a slice to begin with
myType := reflect.TypeOf(my)
slice := reflect.MakeSlice(reflect.SliceOf(myType), 10, 10)
// Create a pointer to a slice value and set it to the slice
x := reflect.New(slice.Type())
x.Elem().Set(slice)
collection.Find(bson.M{}).All(x.Interface())
x.Interface()reflect.ValuexAll()
Why does reflect.MakeSlice return an un-addressable Value?
CanAddr()true
A value is addressable if it is an element of a slice, an element of an addressable array, a field of an addressable struct, or the result of dereferencing a pointer.
reflect.MakeSlice
Why a pointer to a slice?
iter.All
This behaviour is illustrated in this example on play. In essence:
// Works. Uses available storage of the slice.
resultv.Index(1).Set(a)
// Executes but changes are lost:
// reflect.Append(resultv, a)
// Does not work: reflect.Value.Set using unaddressable value
// resultv.Set(reflect.Append(resultv, a))
这篇关于为什么golang反映.MakeSlice返回不可寻址的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!