Home > Article > Backend Development > 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>
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
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!