Can we have function pointers in Go?

前端 未结 5 1612
甜味超标
甜味超标 2021-01-30 12:32

I was learning about pointers in Go. And managed to write something like:

func hello(){

       fmt.Println(\"Hello World\")
}

func main(){

       pfunc := hel         


        
5条回答
  •  我在风中等你
    2021-01-30 13:26

    A different way to approach it is to define an interface

    type command interface {
          DoLoop()
    }
    

    implement a struct that implements it

    type Delete struct {
          instance string
    }
    
    func (dev Delete) DoLoop() {
          fmt.Println("input: delete ")
    }
    

    Create map that contains the struct

     mainFuncTable = make(map[string]command)
     mainFuncTable["delete"] = Delete{"new"}
    

    the call the function

    func route(command string) {
          cmd := mainFuncTable[command]
          cmd.DoLoop()
    }
    

    It's a little indirect but it works

提交回复
热议问题