Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

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 value
package 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.

This post is based on Vicky Kurniawan’s publication https://medium.com/@vicky.kurniawan/go-call-a-function-from-string-name-30b41dcb9e12 which presents a slightly more complex point of view.

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

https://pkg.go.dev/reflect
https://medium.com/@vicky.kurniawan/go-call-a-function-from-string-name-30b41dcb9e12
Category: en-go
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments