回答

收藏

在 Go 中遍历结构体的字段

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

基本上,遍历 a 唯一的字段值方法(据我所知)struct是这样的:* |/ l0 Y* I( p; B5 S
    4 o/ T8 c$ b5 ?1 I$ P1 m# {
  • type Example struct    a_number uint32    a_string string}//...r := &Example{(2 我想知道是否有更好、更通用的实现方法[]interface{}{ r.a_number,r.a_string,},所以我不需要单独列出每个参数,或者有更好的方法来循环遍历结构吗?
    $ Z6 u: F) O0 }6 X
  • 我试图翻阅reflect但是我撞到了墙,因为我不知道怎么拿回来reflect.ValueOf(*r).Field(0).
    " u$ F  y. J( A0 Z, y1 m! Q4 l2 d
  • 谢谢!$ D+ F7 o( I0 T7 i
  •                                                                3 O/ ^7 d2 z& V  N$ e
  •     解决方案:                                                               + C/ ?2 R3 @( O/ \# i/ U
  •                                                                 reflect.Value 使用检索字段后,Field(i)可以调用Interface(). 接口值代表字段值。
    8 g' d" C) T4 n. z# S2 g1 F& l/ C
  • 没有函数可以将字段值转换为特定类型,因为你可能知道,go 中没有泛型。因此,与签名没有任何功能。GetValue() T 与T字段的类型(当然,这取决于字段)。
    ! k0 I  X, X2 v$ g
  • 您可以在 go  中最接近的是GetValue() interface{},这就是所在reflect.Value.Interface() 提供。
    % c3 z% B4 h. r8 b' \
  • 如何使用反射 ( )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)}& u$ [/ O( @1 u' V3 z3 c
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则