Why reflect.MakeSlice Returns Un-Addressable Value
In Go, the reflect package provides an interface to inspect and manipulate types and values. reflect.MakeSlice creates a slice of a given type. However, the returned value is un-addressable. This means that you cannot take its address or assign it to a pointer.
Solution: Using reflect.New()
To obtain an addressable slice using reflection, you can use the reflect.New() function to create a pointer to the slice. This can be done as follows:
// Create the slice type sliceType := reflect.SliceOf(SomeType) // Create a slice using reflect.MakeSlice slice := reflect.MakeSlice(sliceType, 10, 10) // Create a pointer to the slice slicePtr := reflect.New(slice.Type()) // Set the slice pointer to the slice slicePtr.Elem().Set(slice)
Now, you have an addressable slice that can be passed as an argument to functions that require a slice pointer.
Why reflect.MakeSlice Returns Un-Addressable Value
Local stack variables in Go are not addressable because the runtime may move them to the heap at any time. reflect.MakeSlice creates a local slice variable, which is why the returned value is un-addressable.
Why a Pointer to a Slice is Required
Some APIs, such as the one you mentioned from the mgo package, require a pointer to a slice as an argument. This is because when appending to the slice, a new slice with increased capacity may be allocated. If you pass a non-pointer slice, the changes made to the slice will not be visible outside the function.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3