Can we have function pointers in Go?

前端 未结 5 1548
甜味超标
甜味超标 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:13

    You could do it like this:

    package main
    
    import "fmt"
    
    func hello(){
    
           fmt.Println("Hello World")
    }
    
    func main(){
           var pfunc func()
           pfunc = hello     //pfunc is a pointer to the function "hello"
           pfunc()            
    }
    

    If your function has arguments and e.g. a return value, it would look like:

    func hello(name string) int{
    
           fmt.Println("Hello %s", name)
           return 0
    }
    

    and the variable would look like:

      var pfunc func(string)int
    

提交回复
热议问题