GO: Call a function from a string value using reflect
Trying to create a small program in Go, I came across this challenge: How can I call one function or another depending on an obtained value?
Luckily, Go has the reflect package, which allows us to perform this action.
calling a function based on a string valuepackage main import ( "fmt" "reflect" ) func greet(name string) string { return "Welcome to " + name } func main() { functions := make(map[string]interface{}) functions["greet"] = greet function := reflect.ValueOf(functions["greet"]) arguments := []reflect.Value{reflect.ValueOf("Blastcoding.com")} result := function.Call(arguments) fmt.Println(result[0].String()) }
In the previous example, you can see that we used interface{}
data type. This data type allows us to store any type of value in the map.
Note that when we call reflect.ValueOf
, we are creating a reflect.Value.
type Value struct { // contains filtered or unexported fields }
Value is the reflection interface to a Go value, it is a representation of a value of any Go type at runtime. This way we are reflecting our function by making it a dynamic function.
Call calls the function function
with the input arguments as parameters
function.Call(arguments)
Separating the functions from the main() function and using them as routes could be beneficial if we are using Astilectron, for example, since it’s not easy to communicate between Go and JavaScript and vice versa.
package main import ( "fmt" "reflect" ) var functions = map[string]interface{}{ "greet": greet, } func greet(name string) string { return "Welcome to " + name } func main() { function := reflect.ValueOf(functions["greet"]) arguments := []reflect.Value{reflect.ValueOf("Blastcoding.com")} result := function.Call(arguments) fmt.Println(result[0].String()) }
If this post is not what you are looking for, check out Vicky K’s publication, maybe it is what you are looking for.
References