I have an array for which I know the size but not the type at runtime. I would like to convert this array to a reflect.Value
with kind Slice
, so that I could loop over it.
I have created a reflect.SliceHeader
like this:
p := uintptr(unsafe.Pointer(&array))
var data = reflect.SliceOf(originType)
sh := (*reflect.SliceHeader)(unsafe.Pointer(&data))
sh.Data = p
sh.Len = size
sh.Cap = size
runtime.KeepAlive(array) // inform garbage collector not to free the array memory
If I wanted to convert it back to a Slice
of known type T
, I would do:
var slice = *(*[]T)(unsafe.Pointer(sh))
But I my case, I don't know the type. How can I convert this reflect.SliceHeader
to a reflect.Value
with Kind Slice
, so that I could continue to be generic over the underlying type?
Aucun commentaire:
Enregistrer un commentaire