How to invoke a function dynamically using reflection in Golang?

To invoke a function dynamically using reflection in Go, you can follow these steps:

  1. Import the reflect package.

  2. Get a reflect.Value representing the function you want to invoke. You can use the reflect.ValueOf() method to get the reflect.Value of the function. Make sure to pass a function pointer as the argument.

  3. Use the Call() method on the reflect.Value to invoke the function. The Call() method takes a slice of reflect.Value arguments if the function has any parameters. If the function does not have any parameters, you can pass an empty slice.

Here's an example code that demonstrates the dynamic invocation of a function using reflection:

package main import ( "fmt" "reflect" ) func foo() { fmt.Println("Hello, World!") } func add(a, b int) int { return a + b } func main() { // Get the reflect.Value of the "foo" function fooValue := reflect.ValueOf(foo) // Invoke the "foo" function fooValue.Call(nil) // Get the reflect.Value of the "add" function addValue := reflect.ValueOf(add) // Create a slice of reflect.Value arguments args := []reflect.Value{ reflect.ValueOf(10), reflect.ValueOf(5), } // Invoke the "add" function with the arguments result := addValue.Call(args) // Get the returned result from the function invocation sum := result[0].Int() fmt.Println("Addition result:", sum) }

In the above example, the foo() function is invoked dynamically using reflect.ValueOf() and Call(). Similarly, the add() function is invoked with two arguments dynamically. The returned value is extracted using result[0] and converted to int using .Int() method.