Nested Structures and Pass-by-Reference in Reflection
In Go, understanding nested structures and how to pass them by reference in reflection is crucial. Consider a scenario where you have the nested Client and Contact structures:
<code class="go">type Client struct { Id int Age int PrimaryContact Contact Name string } type Contact struct { Id int ClientId int IsPrimary bool Email string }</code>
When you introspect the PrimaryContact field of the Client struct, you may encounter a "reflect.Value.Set using unaddressable value" panic. This is because PrimaryContact is passed by value, not by reference. To resolve this issue, we need to pass PrimaryContact by reference using reflection.
Solution Using Value.Addr()
Code:
<code class="go">package main import ( "fmt" "reflect" ) type Client struct { Id int Age int PrimaryContact Contact Name string } type Contact struct { Id int ClientId int IsPrimary bool Email string } func main() { client := Client{} v := reflect.ValueOf(&client) primaryContact := v.FieldByName("PrimaryContact").Addr() primaryContact.FieldByName("Id").SetInt(123) primaryContact.FieldByName("ClientId").SetInt(456) primaryContact.FieldByName("IsPrimary").SetBool(true) primaryContact.FieldByName("Email").SetString("example@example.com") fmt.Printf("%+v\n", client) }</code>
Output:
{Id:0 Age:0 PrimaryContact:{Id:123 ClientId:456 IsPrimary:true Email:example@example.com} Name:}
Key Points:
The above is the detailed content of How to Pass Nested Structures By Reference in Reflection Using Value.Addr()?. For more information, please follow other related articles on the PHP Chinese website!