type Person struct { Name string Email string } func (p Person) sayHello() string { return fmt.Sprintf("Hello, my name is %s", p.Name) } func main() { p := Person{Name: "John Doe", Email: "[email protected]"} m, ok := reflect.TypeOf(p).MethodByName("sayHello") if !ok { fmt.Println("Method not found") return } methodValue := reflect.ValueOf(p).MethodByName("sayHello") result := methodValue.Call([]reflect.Value{}) fmt.Println(result[0].Interface()) }
type Calculator struct{} func (c Calculator) Add(a, b int) int { return a + b } func main() { c := Calculator{} m, ok := reflect.TypeOf(c).MethodByName("Add") if !ok { fmt.Println("Method not found") return } methodValue := reflect.ValueOf(c).MethodByName("Add") result := methodValue.Call([]reflect.Value{reflect.ValueOf(2), reflect.ValueOf(3)}) fmt.Println(result[0].Interface()) }In this example, we define a `Calculator` struct with an `Add` method that adds two integers. We then use reflection to dynamically find and call the `Add` method on an instance of `Calculator`, passing in two arguments dynamically. The reflect package library is used in both examples to perform dynamic method invocation through the `Type` and `Value` structs returned by `reflect.TypeOf` and `reflect.ValueOf` functions.