以下工作正常:type MyStruct struct { MyField int32}func SetReflectConcrete(obj *MyStruct, fieldName string, newValue interface{}) { objElem := reflect.ValueOf(obj).Elem() field := objElem.FieldByName(fieldName) field.Set(reflect.ValueOf(newValue))}func main() { myStruct := MyStruct{123} SetReflectConcrete(myStruct, "MyField", int32{1234})}如何制作適用SetReflect于任何結(jié)構(gòu)的函數(shù)變體?到目前為止我所有的嘗試都失敗了。簽名會(huì)是這樣的:func SetReflectInterface(obj interface{}, fieldName string, newValue interface{})當(dāng)這樣稱呼它時(shí),這甚至可能嗎SetReflectInterface(myStruct, "MyField", int32{1234})或者它必須被稱為像SetReflectInterface(&myStruct, "MyField", int32{1234})(畢竟,interface{}有一個(gè)指向該結(jié)構(gòu)的指針。)
1 回答

慕尼黑5688855
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
將參數(shù)聲明interface{}為您注意到的類型。將指針傳遞給結(jié)構(gòu)體,如最后一個(gè)代碼片段所示。
func SetReflectConcrete(obj interface{}, fieldName string, newValue interface{}) {
objElem := reflect.ValueOf(obj).Elem()
field := objElem.FieldByName(fieldName)
field.Set(reflect.ValueOf(newValue))
}
myStruct := MyStruct{123}
SetReflectConcrete(&myStruct, "MyField", int32(1234))
反射值必須是可尋址的才能設(shè)置字段。如果直接從結(jié)構(gòu)創(chuàng)建該值將不可尋址。
- 1 回答
- 0 關(guān)注
- 127 瀏覽
添加回答
舉報(bào)
0/150
提交
取消