Go map of functions

前端 未结 6 1529
春和景丽
春和景丽 2020-12-23 09:21

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 wo

6条回答
  •  既然无缘
    2020-12-23 09:48

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

提交回复
热议问题