简体   繁体   English

如何使用Go中的反射设置一个结构成员,该结构成员是一个指向字符串的指针

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

I am trying to use reflection to set a pointer. 我试图使用反射来设置指针。 elasticbeanstalk.CreateEnvironmentInput has a field SolutionStackName which is of type *string . elasticbeanstalk.CreateEnvironmentInput有一个字段SolutionStackName ,其类型为*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

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). Value.SetPointer()只能在值的类型为reflect.UnsafePointer (由Value.Kind()报告)中使用,但是你的是reflect.Ptr因此SetPointer()将发生恐慌(如文档所述)。

Simply use the Value.Set() method to change the value of the struct field (it being pointer or not, doesn't matter). 只需使用Value.Set()方法来更改struct字段的值(它是指针与否,无关紧要)。 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 : 它需要一个类型为reflect.Value的参数,你可以通过调用reflect.ValueOf()获得它,并简单地传递参数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 ): 输出(在Go Playground上试试):

<nil>
teststring

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM