douxu3315 2018-02-07 11:52
浏览 63
已采纳

如何列出指向golang结构所有字段的指针?

Is there a good way in golang to pass all fields of some struct instance c?

I'm looking for some syntactic sugar functionality, so that instead of doing this:

method(&c.field1, &c.field2, &c.field3, &c.field4, &c.field5, ...)

I could do this:

method(FieldsPointers(c)...)

I'm rather new to golang and still learning the basics, if there is no good way to do what I want for a good reason, I'd appreciate an explanation as to why.

  • 写回答

1条回答 默认 最新

  • duanfengwang9157 2018-02-07 12:16
    关注

    Besides all sql specified tools, if you want to access to pointers of a struct, you can use reflect. Be warned that the package is tricky and rob pike said it is not for everyone.

    reflect.Value has methods NumField which returns the numbber of fields in the struct and Field(int) which accepts the index of a field and return the field itself.

    But as you want to set a value to it, it is more complicated than just calling the two methods. Let me show you in code:

    func Scan(x interface{}) {
        v := reflect.ValueOf(x).Elem()
        for i := 0; i < v.NumField(); i++ {
            switch f := v.Field(i); f.Kind() {
            case reflect.Int:
                nv := 37
                f.Set(reflect.ValueOf(nv))
            case reflect.Bool:
                nv := true
                f.Set(reflect.ValueOf(nv))
            }
        }
    }
    

    First, you need to pass a pointer of the struct into Scan, since you are modifying data and the value must be settable. That is why we are calling .Elem(), to dereference the pointer.

    Second, reflect.Value.Set must use a same type to set. You cannot set uint32 to a int64 like normal assignment.

    Playground: https://play.golang.org/p/grvXAc1Px8g

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?