在 Go 中遍历结构体的字段 [英] Iterate through the fields of a struct in Go

查看:70
本文介绍了在 Go 中遍历结构体的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,遍历 struct 字段值的唯一方法(据我所知)是这样的:

Basically, the only way (that I know of) to iterate through the values of the fields of a struct is like this:

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, },所以我不需要列出每个参数单独或替代地,是否有更好的方法来循环遍历结构?

I was wondering, if there's a better and more versatile way of achieving []interface{}{ r.a_number, r.a_string, }, so I don't need to list each parameter individually, or alternatively, is there a better way to loop through a struct?

我试图查看 reflect 包,但我点击了一堵墙,因为我不知道一旦我检索到 reflect.ValueOf(*r).Field(0).

谢谢!

推荐答案

在您使用 Field(i) 检索字段的 reflect.Value 后,您可以得到一个通过调用 Interface() 从中获取接口值.所述接口值则表示字段的值.

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

没有将字段值转换为具体类型的函数,如您所知,没有泛型.因此,没有带有签名的函数 GetValue() TT 是该字段的类型(当然会根据字段而变化).

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

你可以在 Go 中实现的最接近的是 GetValue() interface{} 而这正是 reflect.Value.Interface()优惠.

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

以下代码说明了如何获取结构体中每个导出字段的值使用反射(play):

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

这篇关于在 Go 中遍历结构体的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆