How to Dereference Pointer in Go: Simple Guide with Examples
In Go, you dereference a pointer using the
* operator before the pointer variable. This lets you access or modify the value stored at the memory address the pointer holds.Syntax
To dereference a pointer in Go, use the * operator before the pointer variable. This accesses the value the pointer points to.
var p *int: declares a pointer to an int*p: dereferences the pointer to get or set the int value
go
package main import "fmt" func main() { var p *int var x int = 10 p = &x fmt.Println(*p) // prints 10 }
Output
10
Example
This example shows how to create a pointer to an integer, dereference it to read the value, and modify the value through the pointer.
go
package main import "fmt" func main() { x := 42 p := &x // p points to x fmt.Println(*p) // dereference p to get value: 42 *p = 100 // change value at pointer fmt.Println(x) // x is now 100 }
Output
42
100
Common Pitfalls
Common mistakes include dereferencing a nil pointer, which causes a runtime panic, or confusing the address operator & with the dereference operator *.
Always ensure the pointer is not nil before dereferencing.
go
package main import "fmt" func main() { var p *int // fmt.Println(*p) // panic: dereference of nil pointer x := 5 p = &x fmt.Println(*p) // correct usage: prints 5 }
Output
5
Quick Reference
| Operator | Meaning | Example |
|---|---|---|
| & | Address of a variable | p := &x // p points to x |
| * | Dereference pointer to get/set value | fmt.Println(*p) // prints value at p |
Key Takeaways
Use the * operator before a pointer variable to dereference it in Go.
Dereferencing lets you read or modify the value stored at the pointer's address.
Never dereference a nil pointer to avoid runtime panics.
The & operator gets the address of a variable, while * accesses the value at that address.
Always initialize pointers before dereferencing them.