2016-02-21 54 views
1

我想用反射來設置一個指針。 elasticbeanstalk.CreateEnvironmentInput有一個字段SolutionStackName,它是類型*string。我收到以下錯誤,當我嘗試設置任何值:如何設置一個struct成員,它是一個指向使用反射的字符串轉到

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

這裏是我的代碼:

... 
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 

... 

這裏是日誌輸出

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()只能用如果價值的種類是reflect.UnsafePointer(由Value.Kind()報告),但你的是reflect.Ptr所以SetPointer()將會恐慌(如記錄)。

只需使用Value.Set()方法來更改struct字段的值(它是否爲指針,無關緊要)。該公司預計reflect.Value可從中獲取類型的參數調用reflect.ValueOf(),並簡單地傳遞參數value地址:

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

測試它:

type Config struct { 
    SolutionStackName *string 
} 

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

輸出(嘗試在Go Playground) :

<nil> 
teststring 
+0

非常感謝! –

相關問題