简体   繁体   中英

Set nil *int32 struct field using reflection

I'm trying to set the value of a nil *int through reflection.

In the example below, replaceNilWithNegativeOne should replace any nil *int32 field (tagged with grib:"foo" ) with a pointer to -1.

However, when the code is run, reflect is panicking with panic: reflect: reflect.Value.Set using unaddressable value .

I've seen almost the exact question I'm asking here in several other places, such as:

I know the answer must be in those responses somewhere, but I am still having trouble connecting the dots. I've tried several implementations in addition to the one you see in the example below, but they all seem to either lead to either a segfault, or, more frequently, the unadressable value panic.

It is clear to me that fieldPtr.CanSet() == false , but, that being said, how would I go about accomplishing what it is that I want to accomplish?

Example

// https://play.golang.org/p/yZOtYxwTzUs
package main

import (
    "log"
    "reflect"
    "strings"
)

func main() {
    type testStruct struct {
        SomeField *int32 `grib:"foo"`
    }
    testStructInstance := testStruct{
        SomeField: nil,
    }
    replaceNilWithNegativeOne(testStructInstance)

    if *testStructInstance.SomeField != int32(-1) {
        // We never get here
        log.Println("Didn't get set")
    }
}

func replaceNilWithNegativeOne(obj interface{}) (err error) {
    objType := reflect.TypeOf(obj)
    for i := 0; i < objType.NumField(); i++ {
        if t, ok := objType.Field(i).Tag.Lookup("grib"); ok {
            if strings.Contains(t, "foo") {
                fieldPtr := reflect.ValueOf(obj).Field(i)
                if fieldPtr.Kind() != reflect.Ptr {
                    // do some stuff
                    break
                }
                if fieldPtr.IsNil() {
                    v := -1
                    // I know this isn't working because the CanSet() == false
                    // But I want to set the value to -1.
                    fieldPtr.Set(reflect.ValueOf(&v))
                    continue
                }
            }
        }
    }
    return
}

There are two issues here. The first is that an addressable value is required. Pass a pointer to the struct to the function instead of the the struct value:

replaceNilWithNegativeOne(&testStructInstance)

In the function, call Value.Elem() to get the reflect value for the struct.

The other issue is that the code assigns an int to an int32. Use int32(-1) to fix the problem.

Here's the updated function with these changes:

replaceNilWithNegativeOne(obj interface{}) (err error) {
    v := reflect.ValueOf(obj).Elem()
    t := v.Type()
    for i := 0; i < t.NumField(); i++ {
        if grib, ok := t.Field(i).Tag.Lookup("grib"); ok {
            if strings.Contains(grib, "foo") {
                fv := v.Field(i)
                if fv.Kind() != reflect.Ptr {
                    // do some stuff
                    break
                }
                if fv.IsNil() {
                    iv := int32(-1)
                    fv.Set(reflect.ValueOf(&iv))
                    continue
                }
            }
        }
    }
    return nil
}

Playground Example

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