Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go map of functions

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)     } } 
like image 931
Conceited Code Avatar asked Jul 20 '11 21:07

Conceited Code


People also ask

Does Go have a map function?

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.

What is a Go map?

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.

How do I make a map in Go?

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.


1 Answers

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)         }     } } 
like image 191
peterSO Avatar answered Sep 28 '22 07:09

peterSO