How to use embedding with reflection to dynamically access struct fields and methods in Go?

To use embedding with reflection to dynamically access struct fields and methods in Go, you can follow these steps:

  1. Define a struct that represents the base struct, which contains the common fields and methods shared by other structs. For example:
type Base struct { Field1 int Field2 string } func (b *Base) Method1() { fmt.Println("Method1 called") } func (b *Base) Method2() { fmt.Println("Method2 called") }
  1. Define other structs that embed the base struct and contain their own specific fields and methods. For example:
type Child1 struct { Base Child1Field string } func (c *Child1) Child1Method() { fmt.Println("Child1Method called") } type Child2 struct { Base Child2Field int } func (c *Child2) Child2Method() { fmt.Println("Child2Method called") }
  1. Create an instance of the child struct you want to access dynamically:
child := &Child1{ Base: Base{ Field1: 10, Field2: "Hello", }, Child1Field: "Extra field", }
  1. Access the fields and methods of the child struct dynamically using reflection:
// Accessing struct fields reflectValue := reflect.ValueOf(child) field1 := reflectValue.FieldByName("Field1") fmt.Println("Field1:", field1.Int()) // Accessing struct methods method1 := reflectValue.MethodByName("Method1") method1.Call(nil) // Calling the method // Accessing embedded struct fields baseField2 := reflectValue.FieldByName("Base").FieldByName("Field2") fmt.Println("Base.Field2:", baseField2.String()) // Accessing embedded struct methods baseMethod2 := reflectValue.MethodByName("Base").MethodByName("Method2") baseMethod2.Call(nil) // Calling the method

By using reflection, you can access struct fields and methods dynamically, even when they are embedded within other structs. Note that reflection is powerful but also comes with some performance trade-offs, so use it judiciously.