Go - Dereferencing Pointer
A pointer is a powerful feature in the Golang programming language that allows you to work with the memory addresses.
In Golang, Dereferencing a pointer means accessing the value stored at the memory address pointer is pointing to. This concept is important in Golang as it enables you to optimize performance, share data between functions without copying, and manipulate data.
To declare a pointer, we use the * operator, and to get the memory address of a variable, we can use &(AND) operator.
Following is the way to declare a pointer and assign the memory address for Golang Deferencing Pointers
- var p *int (declares a pointer to an integer)
- p = &x (assigns the memory address of x to the pointer p)
- *p (dereferences the pointer to access the value stored at the memory address)
The Pointers themselves do not have parameters or return values, but functions that use pointers can have parameters and return values involving pointers.
Basic Dereferencing Pointers
Here, we declare an integer variable x and a pointer p that stores the memory address of x. By dereferencing the pointer p, we can access the value of x. So, we can modify the value of x by changing the value stored at the memory address pointed to by p.
Example
package main
import "fmt"
func main() {
var x int = 64
var p *int
p = &x
fmt.Println("Value of x=", x)
fmt.Println("Address of x=", &x)
fmt.Println("Value of p=", p)
fmt.Println("Dereferenced value of p=", *p)
*p = 21
fmt.Println("New value of x=", x)
}
Output
Following is the output of the above program
Value of x= 64 Address of x= 0xc000124010 Value of p= 0xc000124010 Dereferenced value of p= 64 New value of x= 21
Dereferencing Struct Pointers
When you have a pointer to a struct, you can use the * operator or the shorthand -> syntax to access the struct's fields.
Example
package main
import "fmt"
type Student struct {
name string
age int
}
func main() {
p := &Student{"Indu", 18}
fmt.Println("Name=", p.name)
fmt.Println("Age=", (*p).age)
}
Output
Following is the output of the above program
Name= Indu Age= 18
Passing and Dereferencing Pointers in Functions
Functions can take pointers as parameters and dereference them to modify the original values.
Example
package main
import "fmt"
func updateValue(val *int) {
*val = 100
}
func main() {
num := 25
updateValue(&num)
fmt.Println("Updated Value=", num)
}
Output
Following is the output of the above program
Updated Value= 100