This question stems from the need to create a slice address for use in a function that accepts a pointer to a slice.
A loose definition of addressability in Go is that you can take the address of something and are guaranteed that this address points to somewhere meaningful. If you allocate something on the stack in the body of a function, the address of the allocated value will, at some point in time, not be accessible anymore. Therefore, this value is not addressable.
In most cases, Go moves local stack variables to the heap if they are returned or otherwise promoted to the outside, but at runtime this is not done. Therefore, CanAddr() returns only true when:
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.
The stated types all have one thing in common: they guarantee that what they hold will be accessible from everywhere and point to a meaningful value in memory. You have neither a slice element, nor a pointer, nor any of the other mentioned things since you created a local slice using reflect.MakeSlice. The elements of said slice would be addressable though (since the slice's memory resides on the heap).
The simplest solution is probably to use reflect.New() to create the pointer (full example on play):
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())
Note the x.Interface() that was pointed out by other answers as well. This prevents that instead of the reflect.Value the actual value of x is passed to All().
The above is the detailed content of Why does `reflect.MakeSlice` return an un-addressable `Value`?. For more information, please follow other related articles on the PHP Chinese website!