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 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真