Home >Backend Development >Golang >How to Correctly Define and Use a Map of Functions in Go?
Mapping functions to string keys can be a useful tool for organizing and selecting methods in Go. However, a common hurdle is ensuring the correct syntax and typing. Let's explore how to define and utilize a map of functions effectively in Go.
The provided code attempts to create a map with a string key pointing to a function. However, the syntax used in m := map[string] func {...} is incorrect. To define a map of function pointers, the correct syntax is m := map[string]interface{}{...}.
Furthermore, the use of single quotes '' for map keys is not valid. Double quotes "" should be used for string keys.
To demonstrate a working example, consider the following code:
package main import "fmt" func f(p string) { fmt.Println("function f parameter:", p) } func g(p string, q int) { fmt.Println("function g parameters:", p, q) } func main() { m := map[string]interface{}{ "f": f, "g": g, } for k, v := range m { switch k { case "f": v.(func(string))("astring") case "g": v.(func(string, int))("astring", 42) } } }
Here, a map m is created, where each key is a string, and the corresponding value is a function pointer. The switch statement checks the key and casts the value to the appropriate function type before calling the function with the desired parameters. This approach allows for dynamic function selection and execution based on the provided key.
The above is the detailed content of How to Correctly Define and Use a Map of Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!