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 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'