通过 reflect.Value 如何获取切片的底层值?

huangapple go评论85阅读模式
英文:

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")
}

huangapple
  • 本文由 发表于 2015年10月1日 22:28:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/32890137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定