Can we have function pointers in Go?

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

    A function is also a type in Go. So you can essentially create a variable of type func signature. So following would work;

    var pfunc func(string)
    

    This variable can point to any function that take string as argument and returns nothing. Following piece of code works well.

    package main
    
    import "fmt"
    
    func SayHello(to string) {
        fmt.Printf("Hello, %s!\n", to)
    }
    
    func main() {
        var pfunc func(string)
    
        pfunc = SayHello
    
        pfunc("world")
    }
    

提交回复
热议问题