在Go语言中,reflect.SliceOf()的反函数是什么?

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

In Go, what's the inverse of reflect.SliceOf()?

问题

在Go语言中,reflect.SliceOf()函数可以创建一个表示给定类型切片的Type对象:

> SliceOf返回具有元素类型t的切片类型。例如,如果t表示int,那么SliceOf(t)表示[]int。

然而,我已经有一个[]int的Type对象,但我想要得到一个int的Type对象。有没有简单的方法可以做到这一点?(注意,我以int作为示例。实际上,我只知道我有一个切片,我需要找到切片中每个元素的类型。)

我正在尝试使用反射从[]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++ {
        // 这里还有一些其他的代码来填充切片
    }
}

但是为了填充切片,我需要知道正在填充的切片的类型...

英文:

In Go, reflect.SliceOf() makes a Type representing a slice of the given Type:

> SliceOf returns the slice type with element type t. For example, if t represents int, SliceOf(t) represents []int.

However, I already have a Type for []int but want to get a 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.)

I'm trying to populate a slice of bool, int, float, or string, from a []string using reflection... here's the relevant piece:

numElems := len(req.Form[&quot;keyName&quot;])
if structField.Kind() == reflect.Slice &amp;&amp; numElems &gt; 0 {
	slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
	for i := 0; i &lt; 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...

答案1

得分: 5

在你的情况下,你已经有了元素类型:structField.Type()。你可以使用reflect.New(t).Elem()来获取一个可编辑的reflect.Value类型。一旦你填充了该值,你可以调用slice.Index(i).Set(...)将该值分配到结果切片中。

然而,为了回答你的问题,如果你有一个切片并且需要填充它,比如你有一个[]intreflect.Type,那么你可以调用.Elem()来获取intreflect.Type

请参阅Type文档,了解可以在Type上调用的方法。

英文:

In your case, you already have the element type: structField.Type(). You can use reflect.New(t).Elem() to get an "editable" reflect.Value of a type. Once you've populated that value, you can call slice.Index(i).Set(...) to assign that value into the resulting slice.

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.

See the Type documentation for the methods you can call on a Type.

huangapple
  • 本文由 发表于 2014年1月27日 11:40:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/21372654.html
匿名

发表评论

匿名网友

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

确定