Go map of functions

前端 未结 6 1528
春和景丽
春和景丽 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 10:12

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

提交回复
热议问题