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.go44 chars2 lines
Here's an example:
main.go236 chars16 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