Loading, please wait...

A to Z Full Forms and Acronyms

What are Pointers to a Function in Go Programming? | Go Language Tutorial

Nov 20, 2022 #GoProgramming #GoLanguage, 686 Views
In this article, you will learn about what are pointers to a function in Go Programming.

What are Pointers to a Function in Go Programming? | Go Language Tutorial

In this article, you will learn about what are pointers to a function in Go Programming.

Pointers in GoLang is a variable that is used to store the memory address of another variable. The user can also pass the pointers to the function like the variables. There are two ways to pass the pointers to the function. 

  • Create a pointer and simply pass it to the Function:

In the program written below, we are taking a function abc which has an integer-type pointer parameter. It gives the instructions to the function to accept only the pointer-type argument. Fundamentally, the function changed the value of the variable x. Initially, x has a value of 220. But after the function call, the value changed to 680, as visible in the output:

Example:

package main
  
import "fmt"
  
// type pointer as an parameter
func abc(val *int) {
  
    // dereferencing
    *val = 680
}
  
// Main function
func main() {
  
    // normal variable
    var y = 250
        fmt.Printf("The value of y before function call is: %d\n", y)
  
    //assigning the addressof y to it
    var b *int = &y
    // passing pointer to function
    abc(pa)
  
    fmt.Printf("The value of y after function call is: %d\n", y)
}

Output:

The value of y before function call is: 250

The value of y after function call is: 680

  • Passing an address of the variable to the function call:

We are not creating pointers to store the address of the variable i.e, similar to the y variable in the above program. We are passing the address of a to the function call which works as it is discussed above.

Example:

package main
  
import "fmt"
  
// pointer type as an parameter
func abc(val *int) {
  
    // dereferencing
    *val = 680
}
  
// Main function
func main() {
  
    // normal variable
    var y = 220
      
    fmt.Printf("The value of y before function call is: %d\n", y)
    // passing the address ofthe variable y
    ptf(&y)
  
    fmt.Printf("The value of y after function call is: %d\n", y)
  
}
 
Output:
The value of y before function call is: 220
The value of y after function call is: 680
A to Z Full Forms and Acronyms