6

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 ?

Chenglu
  • 1,757
  • 2
  • 14
  • 23

1 Answers1

16

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")
}
  • @mh-cbon: OP was looking for a Slice method that returns a slice of the underlying type, sort of like `Bytes() []bytes`. The `Slice` method on `reflect.Value` returns `Value`, something that isn't of the original type. I've clarified that in my answer. –  Nov 09 '18 at 13:36
  • I think this answer is misleading and that it should clarify that reflect provides the capabilities do deal with the slice, but that for reasons related to the type system there is no shortcut function such `Slice() []` but a fully functional api. imho. –  Nov 09 '18 at 19:25