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

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

问题描述

基本上,遍历 struct 的字段值的唯一方式(我知道的)就是这样的:

  type示例struct {
a_number uint32
a_string string
}

// ...

r:=&示例{(2 <31) - 1,....}:
for _,d:= range [] interface {} { r.a_number,r.a_string,} {
//对d
做些什么}

我想知道,如果有一种更好,更通用的方式来实现 [] interface {} {r.a_number,r.a_string,} ,所以我不需要单独列出每个参数,或者,是否有更好的方法来循环结构?



我试图通过 反映 包裹,但是我撞到了一堵墙,因为我没有当我检索 reflect.ValueOf(* r).Field(0)



谢谢!

reflect.Value 之后,通过使用 Field(i)>解决方案 / code>通过调用 Interface(),可以从中获得
的接口值。所述接口值然后表示字段的
值。

没有函数将字段的值转换为具体类型,因为有$你可能知道的b $ b,没有泛型。因此,签名 GetValue()T
没有函数,其中 T 是字段(当然,这取决于字段的变化)。

您可以实现的最接近的是 GetValue()interface {}

code>,这正是 reflect.Value.Interface()
的优惠信息。



下面的代码演示了如何使用反射来获取struct
中每个导出字段的值(

 导入(
fmt
反映


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

v:= reflect.ValueOf(x)

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

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

fmt.Println(values)
}


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
}

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?

I tried to look through the reflect package, but I hit a wall, because I'm not sure what to do once I retrieve reflect.ValueOf(*r).Field(0).

Thanks!

解决方案

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.

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).

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

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天全站免登陆