donglin1692 2019-01-02 20:28
浏览 35
已采纳

使用反射解引用结构指针和访问字段

I'm writing a recursive function that iterates through every primitive field in a struct.

I need to be able to support fields that are structs, pointers to structs, fields, and pointers to fields.

I've tried doing something like this, where for each field, I first do a check if it's a pointer. If it is, I switch on the type of that instead of just the field itself.

//Get reflect values and types
valOf := reflect.ValueOf(dest).Elem()
typeOf := valOf.Type()

//Iterate through each field
for i := 0; i < valOf.NumField(); i++ {

    var fieldValDeref reflect.Value

    //Get reflect value and type of single field
    fieldVal := valOf.Field(i)
    fieldTyp := typeOf.Field(i)

    //Check if field is a pointer. If so, dereference and switch on dereferenced type
    if fieldVal.Kind() == reflect.Ptr {
        fieldValDeref = fieldVal.Elem()
    } else {
        fieldValDeref = fieldVal
    }


    switch fieldValDeref.Kind() {
    case reflect.Array, reflect.Chan, reflect.Interface, reflect.Func, reflect.Map, reflect.UnsafePointer:
        return errors.New("invalid destination field: " + fieldTyp.Name)

    case reflect.Struct:
        //Recursive call
        break
    default:
        //Perform Action on Field
..................................

The issue I'm getting with this, is that the type of any pointer, struct or not, after calling .Elem() is reflect.Invalid.

How can I first dereference a field (if it is a pointer) and then perform actions accordingly, whether the field is a struct or a primitive?

Thanks

  • 写回答

1条回答 默认 最新

  • doubi3996 2019-01-02 21:16
    关注

    As mkopriva mentioned, dereferencing a nil pointer will always return reflect.Invalid. The solution is to create a new instance first.

    if fieldVal.Kind() == reflect.Ptr {
        fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
        fieldValDeref = fieldVal.Elem()
    } else {
        fieldValDeref = fieldVal
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog