Can we have function pointers in Go?

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

    Go doesn't have the same syntax for function pointers as C and C++ do. There's a pretty good explanation for that on the Go blog. Understandably the Go authors thought C's syntax for function pointers too similar to regular pointers, so in short they decided to make function pointers explicit; i.e. more readable.

    Here's an example I wrote. Notice how the fp parameter is defined in calculate() and the other example below that shows you how you can make a function pointer into a type and use it in a function (the commented calculate function).

    package main
    
    import "fmt"
    
    type ArithOp func(int, int)int
    
    func main() {
        calculate(Plus)
        calculate(Minus)
        calculate(Multiply)
    }
    
    func calculate(fp func(int, int)int) {
        ans := fp(3,2)
        fmt.Printf("\n%v\n", ans) 
    }
    
    // This is the same function but uses the type/fp defined above
    // 
    // func calculate (fp ArithOp) {
    //     ans := fp(3,2)
    //     fmt.Printf("\n%v\n", ans) 
    // }
    
    func Plus(a, b int) int {
        return a + b
    }
    
    func Minus(a, b int) int {
        return a - b
    }
    
    func Multiply(a,b int) int {
        return a * b
    }
    

    The fp parameter is defined as a function that takes two ints and returns a single int. This is somewhat the same thing Mue mentioned but shows a different usage example.

提交回复
热议问题