I read the reflect document and I'm a little confused about why it doesn't have a func (v Value) Slice() slice
function, which to get the underlying value from a reflect.Value which holds a slice in.
Is there a convenient way to get the underlying slice from a reflect.Value ?
There is no Slice() []T
method on reflect.Value
because there is no return value that would be valid for all slice types. For example, Slice() []int
would only work for int slices, Slice() []string
for string slices, etc. Slice() []interface{}
would also not work, due to how the slice is stored in memory.
Instead, you can get the underlying slice value by using the reflect.Value.Interface()
method along with a type assertion:
Example usage:
slice, ok := value.Interface().([]SliceElemType)
if !ok {
panic("value not a []MySliceType")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With