为了账号安全,请及时绑定邮箱和手机立即绑定

反射设置作为 interface{} 传入的结构体字段

反射设置作为 interface{} 传入的结构体字段

Go
守着星空守着你 2023-07-17 14:55:15
以下工作正常: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{}有一个指向该结构的指针。)
查看完整描述

1 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

将参数声明interface{}为您注意到的类型。将指针传递给结构体,如最后一个代码片段所示。


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

在操场上运行它


反射值必须是可寻址的才能设置字段。如果直接从结构创建该值将不可寻址。


查看完整回答
反对 回复 2023-07-17
  • 1 回答
  • 0 关注
  • 55 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信