简体   繁体   中英

Golang mutate a struct's field one by one using reflect

I have a struct like this:

type User struct {
    Name   string
    UID    int
    Bio    string
}

I have a given instantiated struct, and I want to loop through the fields in that object and modify them one by one.

This is what I have so far

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

But I'm getting this error:

panic: reflect: reflect.Value.Set using unaddressable value

Is there a way to do this?

The reflect value is not addressable . Fix by creating the reflect value from a pointer to the struct.

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

Use the following statement to get the field's type. The code in the question gets the type of the reflect.Value, not the type of the value contained within the reflect.Value.

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

Run it on the Go Playground .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM