go - 使用反射和循环修改结构体值

标签 go reflection

我想循环遍历一个结构并使用反射修改字段值。如何设置?

func main() {
    x := struct {
        Foo string
        Bar int
    }{"foo", 2}
    StructCheck(Checker, x)
}

func Checker(s interface{}) interface{} {
    log.Println(s)
    return s
}

func StructCheck(check func(interface{}) interface{}, x interface{}) interface{} {
    v := reflect.ValueOf(x)
    for i := 0; i < v.NumField(); i++ {
        r := check(v.Field(i))
        w := reflect.ValueOf(&r).Elem()

        log.Println(w.Type(), w.CanSet())

        // v.Field(i).Set(reflect.ValueOf(w))

    }
    return v
}

运行 Set() 会导致 panic 并显示:reflect.Value.Set 使用不可寻址的值

最佳答案

您必须将可寻址值传递给该函数。

StructCheck(Checker, &x)

取消引用 StructCheck 中的值:

v := reflect.ValueOf(x).Elem() // Elem() gets value of ptr

还有一些其他问题。这是更新后的代码:

func StructCheck(check func(interface{}) interface{}, x interface{}) {
    v := reflect.ValueOf(x).Elem()
    for i := 0; i < v.NumField(); i++ {
        r := check(v.Field(i).Interface())
        v.Field(i).Set(reflect.ValueOf(r))

    }
}

Run it on the Playground .

关于go - 使用反射和循环修改结构体值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67260295/

相关文章:

go - 将整数 slice 转换为十六进制值的更好方法

amazon-web-services - 在 Go 中为 AWS Lambda 指定多个事件处理程序

scroll - 使用 GXUI 在 Go 中使窗口滚动

c# - 如何防止 Type.GetProperties() 访问对象中的属性

flash - 我有两个类型定义,如何确定一个类型是否是另一个的基类型?

java - 我怎样才能得到一个特定的方法名称作为字符串而不是硬编码方法名称

Java:使用反射注入(inject)字段的最快方法是什么?

go - 创建调用图

go - 结构时间属性不从 Go sqlx 库加载

c# - 如何以编程方式更新 DisplayAttribute 上的 Order 属性?