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

标签 reflection go

在围棋中,reflect.SliceOf()制作一个表示给定类型的 slice 的类型:

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

但是,我已经有了 []int 的类型,但想获得 int 的类型。有没有简单的方法可以做到这一点? (请注意,我以 int 为例。实际上,我所知道的只是我有一个 slice ,我需要找到 slice 中每个元素的类型。)

我正在尝试使用反射从 []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
    }
}

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

最佳答案

在您的例子中,您已经拥有元素类型:structField.Type()。您可以使用 reflect.New(t).Elem() 获取类型的“可编辑”reflect.Value。填充该值后,您可以调用 slice.Index(i).Set(...) 将该值分配给生成的 slice 。

不过,要回答你的问题,如果你确实有一个 slice 并需要填充它,假设你有一个 []intreflect.Type ,然后您可以调用 .Elem() 来获取 intreflect.Type

参见 Type您可以在类型上调用的方法的文档。

关于reflection - 在 Go 中,reflect.SliceOf() 的反函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372654/

相关文章:

html - 如何在golang中获取<ul>的表单值?

go - 有没有办法在 Go 中判断文件类型(可执行文件、文本等)?

dictionary - 使用 Golang 将包含结构体作为值的映射导出到 csv

JAVA使用反射创建嵌套静态类的实例

Java反射方法 self 认识

c - 将程序状态导出到 procfs?

database - 在 Go 中模拟数据库/sql 结构

arrays - panic : SetUint using value obtained using unexported field

c# - 如何通过反射过滤任何属性的集合?

algorithm - 二维圆矩形碰撞和反射不起作用