以下工作正常:
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于任何结构的函数变体?到目前为止我所有的尝试都失败了。签名会是这样的:
func SetReflectInterface(obj interface{}, fieldName string, newValue interface{})
当这样称呼它时,这甚至可能吗
SetReflectInterface(myStruct, "MyField", int32{1234})
或者它必须被称为像
SetReflectInterface(&myStruct, "MyField", int32{1234})
(毕竟,interface{}有一个指向该结构的指针。)
慕尼黑5688855
相关分类