How to set a struct member that is a pointer to a string using reflection in Go

喜夏-厌秋 提交于 2021-02-20 18:53:07

问题


I am trying to use reflection to set a pointer. elasticbeanstalk.CreateEnvironmentInput has a field SolutionStackName which is of type *string. I am getting the following error when I try to set any value:

panic: reflect: call of reflect.Value.SetPointer on ptr Value

Here is my code:

    ...
newEnvCnf := new(elasticbeanstalk.CreateEnvironmentInput)
checkConfig2(newEnvCnf, "SolutionStackName", "teststring")
    ...
func checkConfig2(cnf interface{}, key string, value string) bool {
    log.Infof("key %v, value %s", key, value)

    v := reflect.ValueOf(cnf).Elem()
    fld := v.FieldByName(key)

    if fld.IsValid() {
        if fld.IsNil() && fld.CanSet() {
            fld.SetPointer(unsafe.Pointer(aws.String(value)))
//aws.String returns a pointer

...

Here is the log output

time="2016-02-20T23:54:52-08:00" level=info msg="key [SolutionStackName], value teststring" 
    panic: reflect: call of reflect.Value.SetPointer on ptr Value [recovered]
        panic: reflect: call of reflect.Value.SetPointer on ptr Value

回答1:


Value.SetPointer() can only be used if the value's kind is reflect.UnsafePointer (as reported by Value.Kind()), but yours is reflect.Ptr so SetPointer() will panic (as documented).

Simply use the Value.Set() method to change the value of the struct field (it being pointer or not, doesn't matter). It expects an argument of type reflect.Value which you can obtain by calling reflect.ValueOf(), and simply pass the address of the parameter value:

fld.Set(reflect.ValueOf(&value))

Testing it:

type Config struct {
    SolutionStackName *string
}

c := new(Config)
fmt.Println(c.SolutionStackName)
checkConfig2(c, "SolutionStackName", "teststring")
fmt.Println(*c.SolutionStackName)

Output (try it on the Go Playground):

<nil>
teststring


来源:https://stackoverflow.com/questions/35533837/how-to-set-a-struct-member-that-is-a-pointer-to-a-string-using-reflection-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!