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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?