"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Obtain Field Addresses in Nested Structures Using Reflection?

How to Obtain Field Addresses in Nested Structures Using Reflection?

Published on 2024-11-10
Browse:844

How to Obtain Field Addresses in Nested Structures Using Reflection?

Obtaining Field Addresses in Nested Structures Using Reflection

In this scenario, you wish to traverse and examine nested structures and obtain the addresses of non-pointer fields within them. Using reflection, you have a function that iterates through fields but encounters difficulties obtaining the memory address of non-pointer fields located in embedded substructures.

To rectify this issue, it's crucial to note that valueField.Interface() does not provide the expected outcome because it returns the actual value stored within the field, which is not valid when working with non-pointer types.

The solution lies in modifying the InspectStructV function to receive a reflect.Value instead of an interface{}. This allows you to directly manipulate the reflection object and retrieve the address of the field. Additionally, when recursively calling InspectStructV for struct fields, valueField, which previously held the interface value, now directly points to the reflection value for the nested structure, ensuring that the address can be retrieved correctly.

Here's the revised code snippet:

func InspectStructV(val reflect.Value) {
    if val.Kind() == reflect.Interface && !val.IsNil() {
        elm := val.Elem()
        if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr {
            val = elm
        }
    }
    if val.Kind() == reflect.Ptr {
        val = val.Elem()
    }

    for i := 0; i 

By making these changes, you'll be able to successfully retrieve the memory addresses of non-pointer fields even when they reside within nested structures.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3