duandeng1824 2017-09-21 23:17
浏览 35
已采纳

当字段是指向x的指针时,使用反射设置结构字段的值

I've checked quite a lot of reflect questions and I've used it quite a bit now but I've not found a solution for this.

Basically, I have a struct of pointers to various primitives. The struct is a config for an application and the reason the fields are pointers is so I can determine between a field set to the default and a field that hasn't been set at all - to enforce "required" fields.

I'll link the source code at the end but lets use a simple example for now:

type Config struct {
    A *string
    B *int
    C *bool
    D *[]string // wildcard!
}

So I grab the reflect.Value via reflect.ValueOf(*cfg) which gives me a .Field on each element, which I iterate through.

The thing is, each element doesn't pass CanAddr or CanSet, I can't seem to find a way to set the value held behind the pointer. Is this a limitation of the language? Will I need to make my fields non-pointers? That would suck as there would be no way to determine if a user specified an empty string or just didn't set it at all for example.

Oh and bonus points for setting/appending a []string field! That one confused me even without pointers thrown in the mix!

Anyway, the relevant code is here: https://github.com/Southclaws/sampctl/blob/master/settings.go#L95-L116

  • 写回答

1条回答 默认 最新

  • doutuo4285 2017-09-21 23:57
    关注

    Replace these lines:

    t := reflect.TypeOf(*cfg)
    v := reflect.ValueOf(*cfg)
    

    with

    v := reflect.ValueOf(cfg).Elem()
    t := v.Type()
    

    to get an addressable value.

    The value created by reflect.ValueOf(*cfg) has no reference to addressable memory. The fix is to dereference the pointer in the reflect domain.

    Regarding the []string. Because there's a difference between a null slice and an empty slice, there may be no need to use *[]string. In any case, use the reflect.Append function to append to a slice:

    var s []string
    v := reflect.ValueOf(&s).Elem()
    v.Set(reflect.Append(v, reflect.ValueOf("hello")))
    v.Set(reflect.Append(v, reflect.ValueOf("world")))
    fmt.Println(s) // prints [hello world]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计