Go map of functions

m := map[string]func(string, string)

Works if you know the signature (and all the funcs have the same signature) I think this is cleaner/safer than using interface{}


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)
        }
    }
}

You can define a type if functions are same interface.

package main

import "log"

type fn func (string)

func foo(msg string) {
  log.Printf("foo! Message is %s", msg)
}

func bar(msg string) {
  log.Printf("bar! Message is %s", msg)
}

func main() {
  m := map[string] fn {
    "f": foo,
    "b": bar,
  }
  log.Printf("map is %v", m)
  m["f"]("Hello")
  m["b"]("World")
}