Przejdź mapę funkcji

Mam program Go, który ma zdefiniowaną funkcję. Mam również mapę, która powinna mieć klucz dla każdej funkcji. Jak mogę to zrobić?

Próbowałem tego, ale to nie działa.
func a(param string) {

}

m := map[string] func {
    'a_func': a,
}

for key, value := range m {
   if key == 'a_func' {
    value(param) 
   }
}
Author: Conceited Code, 2011-07-21

4 answers

Próbujesz zrobić coś takiego? Poprawiłem przykład, aby używać różnych typów i liczby parametrów funkcji.

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)
        }
    }
}
 43
Author: peterSO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-21 02:21:12
m := map[string]func(string, string)

Działa, jeśli znasz podpis (i wszystkie funkcje mają ten sam podpis) Myślę, że jest to czystsze/bezpieczniejsze niż korzystanie z interfejsu{}

 28
Author: Seth Hoenig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-15 16:06:19

Można zdefiniować typ, jeśli funkcje są tym samym interfejsem.

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")
}
 9
Author: smagch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-19 18:05:02

@odpowiedź Setha Hoeniga pomogła mi najlepiej, ale chciałem tylko dodać, że Go akceptuje również funkcje o zdefiniowanej wartości zwrotnej:

package main

func main() {
    m := map[string]func(string) string{
        "foo": func(s string) string { return s + "nurf" },
    }

    m["foo"]("baz") // "baznurf"
}

Jeśli uważasz, że jest brzydki, zawsze możesz użyć typu (zobacz odpowiedź @ smagch ).

 3
Author: tleb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-21 12:15:31