2

I wanted to loop through a struct and modify fields value using reflection. How can I Set it?

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
}

Running Set() causes panic and shows :reflect.Value.Set using unaddressable value

0

1 Answer 1

4

You must pass an addressable value to the function.

StructCheck(Checker, &x)

There's

Dereference the value in the StructCheck:

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

There were some other issues. Here's the updated code:

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But when I try to cast it to x's struct it panics again any way to fix this? link
@ned I edited the answer to remove the return value from StructCheck. Because the caller already has the value, there's no need to get the value again from the return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.