[英]In Go, what's the inverse of reflect.SliceOf()?
In Go, reflect.SliceOf()
makes a Type representing a slice of the given Type: 在Go中,
reflect.SliceOf()
使一个Type表示给定Type的切片:
SliceOf returns the slice type with element type t.
SliceOf返回元素类型为t的切片类型。 For example, if t represents int, SliceOf(t) represents []int.
例如,如果t表示int,则SliceOf(t)表示[] int。
However, I already have a Type for []int
but want to get a Type for int
. 但是,我已经有一个Type for
[]int
但是想要获得一个Type for int
。 Is there an easy way to do that? 有一个简单的方法吗? (Note, I'm using
int
as an example. In reality, all I know is I have a slice, and I need to find what Type each element of the slice is.) (注意,我使用
int
作为示例。实际上,我所知道的是我有一个切片,我需要找到切片的每个元素的类型。)
I'm trying to populate a slice of bool, int, float, or string, from a []string
using reflection... here's the relevant piece: 我正在尝试使用反射从
[]string
填充bool,int,float或string的切片...这是相关的部分:
numElems := len(req.Form["keyName"])
if structField.Kind() == reflect.Slice && numElems > 0 {
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
for i := 0; i < numElems; i++ {
// I have some other code here to fill out the slice
}
}
But in order to fill out the slice, I need to know the type of the slice I'm filling out... 但是为了填写切片,我需要知道我填写的切片的类型...
In your case, you already have the element type: structField.Type()
. 在您的情况下,您已经拥有元素类型:
structField.Type()
。 You can use reflect.New(t).Elem()
to get an "editable" reflect.Value
of a type. 您可以使用
reflect.New(t).Elem()
来获得“可编辑”的reflect.Value
类型。 Once you've populated that value, you can call slice.Index(i).Set(...)
to assign that value into the resulting slice. 填充该值后,可以调用
slice.Index(i).Set(...)
将该值分配给生成的切片。
To answer the letter of your question though, if you do have a slice and need to populate it, say you have a reflect.Type
of a []int
, then you can call .Elem()
to get the reflect.Type
for int
. 要回答你的问题的字母,如果你有一个切片并需要填充它,假设你有一个
[]int
的reflect.Type
,那么你可以调用.Elem()
来获取int
的reflect.Type
。
See the Type documentation for the methods you can call on a Type. 有关可在Type上调用的方法,请参阅类型文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.