How to use a pointer in a function in GoLang
In this article, you will learn about how to use a pointer in a function in the Go language.
A pointer is nothing but an object that stores a memory address. Like many programming languages, the Go language also has the functionality of a pointer. In the Go language, pointers are used as a variable that stores the memory address of another variable. You may also use a pointer in a function. Let’s see how you can do this in the below section.
package main
import "fmt"
func myPointerFunc(x *int) {
*x = 17
}
func main() {
var age = 21
fmt.Println("The value of age before using Pointer is : ", age)
var pAge *int = &age
myPointerFunc(pAge)
fmt.Println("The value of age after using Pointer is: ", age)
}
/*
Output:
The value of age before using Pointer is : 21
The value of age after using Pointer is: 17
*/
Here, we have taken myPointerFunc() that expected an integer type pointer parameter and you can see that the value of age 21 before using the pointer function and after using it the value has changed and shows 17.
You may also use a pointer in the Go language function by parsing it into the address of a variable to the function call. Let’s see the below code example where we have directly passed the address of the age into the function call.
package main
import "fmt"
func myPointerFunc(x *int) {
*x = 17
}
func main() {
var age = 21
fmt.Println("The value of age before using Pointer is : ", age)
myPointerFunc(&age)
fmt.Println("The value of age after using Pointer is: ", age)
}
/*
Output:
The value of age before using Pointer is : 21
The value of age after using Pointer is: 17
*/
You can see that we are getting the same results as before but by following a different approach and these are the ways of using a pointer in a function in the Go language.