Go: Call a Function from String Name

Vicky Kurniawan
2 min readNov 15, 2019

This is for all of you who have been kind of fuzzy about to create dynamic logic functions based on your business process.

1. Overview

In this short article, we’ll take a quick look at how to call a function from a string name using the Golang Reflection Call.

2. Introduction

Basically, we could store the function name into the hash table using Go maps.
A Go map is equivalent to the well-known hash table found in many other programming languages. The main advantage of maps is that they can use any data type as their index, which in this case is called a map key or just a key.

3. Getting Ready

Let’s create a simple Go map which we’ll use for the examples that follow:

from the above code, the someOtherFunction function is an orchestra to call other functions based on the map key value that has been determined in the main function.
It should be enough if we want to call a function with the same input-output data-type. Then what if we want to call multiple functions with different input-output data-type? we could use interface{}.

...funcs := map[string]interface{} {
"keyword1": keyword1,
"keyword2": keyword2,
}
...

We can’t call a function stored in an empty interface variable directly. Then How to call the function? we should create one function to call the interface using a reflection call.
we could add functions with different input-output data-type into one map:

...
type stubMapping map[string]interface{}
var StubStorage = stubMapping{}
func Call(funcName string, params ... interface{}) (result interface{}, err error) {
f := reflect.ValueOf(StubStorage[funcName])
if len(params) != f.Type().NumIn() {
err = errors.New("The number of params is out of index.")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
var res []reflect.Value
res = f.Call(in)
result = res[0].Interface()
return
}
...

Value.Call() returns the return values of the function call as a []reflect.Value. You may use the Value.Interface() method to get the value represented by a reflect.Value as an interface{} value. From there, you may use type assertion to obtain values of different types.

This is the whole code:

4. Conclusion

In this quick article, we’ve seen how to call a function from a string name at runtime through reflection. this is an approach using reflection that allows to pass a flexible number of arguments as well.

As always, the example code can be found over on Github.

--

--