Friday, November 15, 2024
Google search engine
HomeLanguagesGolangPassing Pointers to a Function in Go

Passing Pointers to a Function in Go

Prerequisite: Pointers in Go

Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. You can also pass the pointers to the function like the variables. There are two ways to do this as follows:

Create a pointer and simply pass it to the Function

In the below program we are taking a function ptf which have integer type pointer parameter which instructs the function to accept only the pointer type argument. Basically, this function changed the value of the variable x. At starting x contains the value 100. But after the function call, value changed to 748 as shown in the output. 

Go




// Go program to create a pointer
// and passing it to the function
package main
  
import "fmt"
  
// taking a function with integer
// type pointer as an parameter
func ptf(a *int) {
  
    // dereferencing
    *a = 748
}
  
// Main function
func main() {
  
    // taking a normal variable
    var x = 100
  
        fmt.Printf("The value of x before function call is: %d\n", x)
  
    // taking a pointer variable
    // and assigning the address
    // of x to it
    var pa *int = &x
  
    // calling the function by
    // passing pointer to function
    ptf(pa)
  
    fmt.Printf("The value of x after function call is: %d\n", x)
  
}


Output:

The value of x before function call is: 100
The value of x after function call is: 748

Passing an address of the variable to the function call

Considering the below program, we are not creating a pointer to store the address of the variable x i.e. like pa in the above program. We are directly passing the address of x to the function call which works like the above-discussed method. 

Go




// Go program to create a pointer
// and passing the address of the
// variable to the function
package main
  
import "fmt"
  
// taking a function with integer
// type pointer as an parameter
func ptf(a *int) {
  
    // dereferencing
    *a = 748
}
  
// Main function
func main() {
  
    // taking a normal variable
    var x = 100
      
    fmt.Printf("The value of x before function call is: %d\n", x)
  
    // calling the function by
    // passing the address of
    // the variable x
    ptf(&x)
  
    fmt.Printf("The value of x after function call is: %d\n", x)
  
}


Output:

The value of x before function call is: 100
The value of x after function call is: 748

Note: You can also use the short declaration operator(:=) to declare the variables and pointers in above programs.
 

RELATED ARTICLES

Most Popular

Recent Comments