I have Go program that has a function defined. I also have a map that should have a key for each function. How can I do that?
I have tried this, but this doesn't work.
func a(param string) { } m := map[string] func { 'a_func': a, } for key, value := range m { if key == 'a_func' { value(param) } }
Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.
In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.
Go by Example: Maps To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.
Are you trying to do something like this? I've revised the example to use varying types and numbers of function parameters.
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) } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With