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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化