To dereference a pointer in Go, use the asterisk (*) operator on the pointer variable to access the underlying value it points to. This allows you to read or modify the original variable directly through the pointer.
Here is a simple example showing how to read and modify a value via a pointer:
package main
import "fmt"
func main() {
age := 25
ptr := &age // Create a pointer to 'age'
// Dereference to read the value
fmt.Println("Current age:", *ptr) // Output: 25
// Dereference to modify the value
*ptr = 26
fmt.Println("Updated age:", age) // Output: 26
}
You can also pass pointers to functions to modify the original variable without returning a new value. This is common when you need to update state across function boundaries:
package main
import "fmt"
func increment(n *int) {
*n++ // Dereference and increment
}
func main() {
count := 10
increment(&count)
fmt.Println(count) // Output: 11
}
Important Safety Note: Dereferencing a nil pointer causes a runtime panic. Always ensure the pointer is not nil before dereferencing, especially when dealing with pointers returned from functions or stored in data structures.
func safeDeref(p *int) {
if p != nil {
fmt.Println(*p)
} else {
fmt.Println("Pointer is nil")
}
}
In Go, the * operator is the only way to access the value behind a pointer. If you need the address of a variable again, use the & operator. Remember that pointers are distinct from the values they point to; assigning a pointer to another variable copies the address, not the value.