To use embedding with reflection to dynamically access struct fields and methods in Go, you can follow these steps:
type Base struct {
Field1 int
Field2 string
}
func (b *Base) Method1() {
fmt.Println("Method1 called")
}
func (b *Base) Method2() {
fmt.Println("Method2 called")
}
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")
}
child := &Child1{
Base: Base{
Field1: 10,
Field2: "Hello",
},
Child1Field: "Extra field",
}
// 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.