douguai6716 2018-04-11 00:14
浏览 41
已采纳

使用反射设置nil * int32结构域

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
}
  • 写回答

1条回答 默认 最新

  • doudu9652 2018-04-11 00:25
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。