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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据