Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get slice underlying value via reflect.Value

Tags:

reflection

go

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 ?

like image 361
Chenglu Avatar asked Dec 11 '22 20:12

Chenglu


1 Answers

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")
}
like image 132
Tim Cooper Avatar answered Dec 31 '22 02:12

Tim Cooper