Home > Backend Development > Golang > How to Get a Pointer to a Value Using Reflection in Go?

How to Get a Pointer to a Value Using Reflection in Go?

Mary-Kate Olsen
Release: 2024-11-01 15:23:02
Original
629 people have browsed it

How to Get a Pointer to a Value Using Reflection in Go?

Get Pointer to Value Using Reflection

Inspecting the fields of an interface requires the use of reflection in Go. However, challenges arise when attempting to retrieve the address of non-pointer fields. This article addresses those challenges and provides a solution.

In the code sample provided, a function named InspectStruct traverses a given structure and outputs details about each field. While most fields are accounted for, non-pointer fields embedded at higher levels within the structure yield "not-addressable" results.

Solution

The issue lies in the usage of reflect.Value.Interface() method. To obtain the address of a non-pointer field, it is recommended to pass reflect.Value instead of interface{} to the InspectStruct function. The corrected code below incorporates this change:

<code class="go">func InspectStructV(val reflect.Value) {
    // ... (remaining code is identical)
}

func InspectStruct(v interface{}) {
    InspectStructV(reflect.ValueOf(v))
}</code>
Copy after login

With this modification, the InspectStruct function operates as intended, yielding the addresses of all fields within the structure, regardless of their depth or pointer status. This can be seen in the updated test results:

Field Name: Id,  Field Value: 1,     Address: 0x408125440 , Field type: int   , Field kind: int
Field Name: F,   Field Value: {2 {3}},   Address: 0x408125444 , Field type: main.V    , Field kind: struct
Field Name: Id,  Field Value: 2,     Address: 0x408125450 , Field type: int   , Field kind: int
Field Name: F,   Field Value: {3},   Address: 0x408125458 , Field type: main.Z    , Field kind: struct
Field Name: Id,  Field Value: 3,     Address: 0x408125460 , Field type: int   , Field kind: int
Copy after login

The above is the detailed content of How to Get a Pointer to a Value Using Reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template