在 Go 中遍历结构的字段

新手上路,请多包涵

基本上,(据我所知)遍历 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 许可协议

阅读 955
2 个回答

使用 reflect.Value 检索字段的 Field(i) 后,你可以通过调用 Interface() 从中获取接口值所述接口值则代表该字段的值。

没有将字段的值转换为具体类型的函数,因为您可能知道,go 中没有泛型。因此,没有带有签名 GetValue() T 的函数,其中 T 是该字段的类型(当然会根据字段的不同而变化)。

您可以在 go 中实现的最接近的是 GetValue() interface{} 而这正是 reflect.Value.Interface() 提供的。

以下代码说明了如何使用反射 ( 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)
}

原文由 nemo 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你想遍历结构的字段和值,那么你可以使用下面的 Go 代码作为参考。

 package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

操场 上奔跑

注意: 如果您的结构中的字段未导出,则 v.Field(i).Interface() 会出现恐慌 panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

原文由 Chetan Kumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题