回答

收藏

在 Go 中遍历结构体的字段

技术问答 技术问答 238 人阅读 | 0 人回复 | 2023-09-12

基本上,遍历 a 唯一的字段值方法(据我所知)struct是这样的:- e, X, b/ c+ M* b7 E5 q" x$ A
    1 r' n" X9 k' r9 Y9 X) S
  • type Example struct    a_number uint32    a_string string}//...r := &Example{(2 我想知道是否有更好、更通用的实现方法[]interface{}{ r.a_number,r.a_string,},所以我不需要单独列出每个参数,或者有更好的方法来循环遍历结构吗?
    - n& f! Q4 T5 ^
  • 我试图翻阅reflect但是我撞到了墙,因为我不知道怎么拿回来reflect.ValueOf(*r).Field(0).
    & M& k! \. v5 ?4 `
  • 谢谢!
    + U9 O: [9 M. U9 X5 q
  •                                                                  h. N5 Y+ [, h* x
  •     解决方案:                                                                 L" |3 T9 |9 k+ I! b% _
  •                                                                 reflect.Value 使用检索字段后,Field(i)可以调用Interface(). 接口值代表字段值。* }0 B% D9 V) @% Y0 p
  • 没有函数可以将字段值转换为特定类型,因为你可能知道,go 中没有泛型。因此,与签名没有任何功能。GetValue() T 与T字段的类型(当然,这取决于字段)。
    " M: d+ g: R  H6 L3 x
  • 您可以在 go  中最接近的是GetValue() interface{},这就是所在reflect.Value.Interface() 提供。
    ; p$ u4 d" ]9 D7 G+ a
  • 如何使用反射 ( )play ) 在结构中获得每个导出字段的值:[code]import  &quot;fmt&quot;    &quot;reflect&quot;)func main()      x := struct{Foo string; Bar int }{&quot;foo&quot;,2}    v := reflect.ValueOf(x)    values := make([]interface{},v.NumField()    for i := 0; i < v.NumField(); i                                                                                                                                                                                     values = v.Field(i).Interface()      fmt.Println(values)}8 I" z5 k& i) H& [6 T
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则