基本上,(据我所知)遍历 a struct
的字段值的唯一方法是这样的:
type Example struct {
a_number uint32
a_string string
}
//...
r := &Example{(2 << 31) - 1, "...."}:
for _, d:= range []interface{}{ r.a_number, r.a_string, } {
//do something with the d
}
我想知道,是否有更好、更通用的方法来实现 []interface{}{ r.a_number, r.a_string, }
,所以我不需要单独列出每个参数,或者,是否有更好的方法来遍历结构?
我试图查看 reflect
包,但我碰壁了,因为我不确定一旦检索到 reflect.ValueOf(*r).Field(0)
之后该怎么做。
谢谢!
原文由 omninonsense 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
reflect.Value
检索字段的Field(i)
后,你可以通过调用Interface()
从中获取接口值所述接口值则代表该字段的值。没有将字段的值转换为具体类型的函数,因为您可能知道,go 中没有泛型。因此,没有带有签名
GetValue() T
的函数,其中T
是该字段的类型(当然会根据字段的不同而变化)。您可以在 go 中实现的最接近的是
GetValue() interface{}
而这正是reflect.Value.Interface()
提供的。以下代码说明了如何使用反射 ( play ) 获取结构中每个导出字段的值: