英文:
How to get slice underlying value via reflect.Value
问题
我阅读了reflect文档,对于为什么它没有一个func (v Value) Slice() slice
函数有些困惑,这个函数可以从一个包含切片的reflect.Value中获取底层值。
有没有一种方便的方法可以从reflect.Value中获取底层切片呢?
英文:
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 ?
答案1
得分: 16
reflect.Value
上没有Slice() []T
方法,因为没有一个返回值适用于所有切片类型。例如,Slice() []int
只适用于int切片,Slice() []string
只适用于string切片,等等。Slice() []interface{}
也不适用,因为切片在内存中的存储方式不同。
相反,你可以使用reflect.Value.Interface()
方法和类型断言来获取底层切片值:
示例用法:
slice, ok := value.Interface().([]SliceElemType)
if !ok {
panic("value not a []MySliceType")
}
英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论