Can we have function pointers in Go?

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

    It works if you're using the signature. There's no pointer.

    type HelloFunc func(string)
    
    func SayHello(to string) {
        fmt.Printf("Hello, %s!\n", to)
    }
    
    func main() {
        var hf HelloFunc
    
        hf = SayHello
    
        hf("world")
    }
    

    Alternatively you can use the function signature directly, without declaring a new type.

提交回复
热议问题