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

Golang 使用反射对结构体的字段进行一一变异

Golang 使用反射对结构体的字段进行一一变异

Go
温温酱 2023-07-04 09:59:02
我有一个这样的结构:type User struct {    Name   string    UID    int    Bio    string}我有一个给定的实例化结构,我想循环遍历该对象中的字段并一一修改它们。这就是我到目前为止所拥有的user := User{    Name: "Test",    UID:  1,    Bio:  "Test bio",}reflectVal := reflect.ValueOf(user)numFields := reflectVal.NumField()for i := 0; i < numFields; i++ {    fieldType := reflect.TypeOf(reflectVal.Field(i))    reflectVal.Field(i).Set(reflect.Zero(fieldType))    ...}但我收到这个错误:panic: reflect: reflect.Value.Set using unaddressable value有没有办法做到这一点?
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

反射值不可寻址。通过从指向结构的指针创建反射值来修复。

reflectVal := reflect.ValueOf(&user).Elem()

使用以下语句获取字段的类型。问题中的代码获取reflect.Value 的类型,而不是reflect.Value 中包含的值的类型。

fieldType := reflectVal.Field(i).Type()


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

添加回答

举报

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