登录
首页 >  Golang >  Go问答

使用 interface{} 传递结构体字段的反射设置

来源:stackoverflow

时间:2024-03-03 19:39:24 212浏览 收藏

你在学习Golang相关的知识吗?本文《使用 interface{} 传递结构体字段的反射设置》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

以下工作正常:

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{} 有一个指向结构体的指针。)


解决方案


如您所述,将参数声明为 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))

Run it on the playground

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

理论要掌握,实操不能落!以上关于《使用 interface{} 传递结构体字段的反射设置》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>