I was learning about pointers in Go. And managed to write something like:
func hello(){
fmt.Println(\"Hello World\")
}
func main(){
pfunc := hel
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.