Home >Backend Development >Golang >Why does reflect.MakeSlice return an un-addressable value?
To retrieve a pointer to a slice using reflection, utilize reflect.New():
my := &My{} myType := reflect.TypeOf(my) slice := reflect.MakeSlice(reflect.SliceOf(myType), 10, 10) x := reflect.New(slice.Type()) x.Elem().Set(slice)
Remember to use x.Interface() to prevent passing the reflect.Value instead of the actual value to your function.
An addressable value ensures that its address points to a meaningful location. Allocations made on the stack within a function do not guarantee this, hence they are not addressable.
reflect.MakeSlice assigns values to a local slice on the heap without addressing them as elements of arrays, structs, or dereferenced pointers. Therefore, it returns an un-addressable Value.
Often, in functions like mgo's iter.All, pointers are necessary because slices are often appended to. Appending changes the slice's memory address, which needs to be communicated to the caller.
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!