create a pointer to a function in go

In Go, we can create a pointer to a function using the function type and the address-of operator.

The syntax to declare a function pointer is:

main.go
var functionPtr *func(arguments) returnType
44 chars
2 lines

Here's an example:

main.go
package main

import "fmt"

func foo(a, b int) {
    fmt.Println(a + b)
}

func main() {
    //declare a pointer to the foo function
    var bar *func(a, b int) = &foo
    
    //call the function through the pointer
    (*bar)(1, 2)
}
236 chars
16 lines

In this example, we declare a function foo that takes two integers and prints their sum. Then, in the main function, we declare a pointer to a function that takes two integers and has no return value. We initialize this pointer with the address of the foo function. Finally, we call foo through the bar pointer by dereferencing it with *bar and passing the arguments 1 and 2. The output of the program will be 3.

gistlibby LogSnag