Pointer Basics
In this page:
What Is a Pointer?
A pointer variable stores the memory address of another value, rather than the value itself. In Go, a pointer to a type T is written *T, and you obtain one with the & (address-of) operator on an existing value.
Example: What Is a Pointer?
package main
import "fmt"
func main() {
x := 10
p := &x
fmt.Println("value of x:", x)
fmt.Println("address stored in p:", p)
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing a Pointer
Dereferencing with *p retrieves the actual value stored at the address a pointer holds -- it's the operation that goes 'follow this address and give me what's there'.
Example: Dereferencing a Pointer
package main
import "fmt"
func main() {
x := 10
p := &x
fmt.Println("dereferenced value:", *p)
}
Login to try C/C++/Java/PHP code in the editor
Pointers Enable Automatic Garbage Collection
Unlike C, Go manages memory for you -- you never manually free a pointer's memory. The garbage collector tracks when a value is no longer reachable through any pointer and reclaims it automatically.
Example: Pointers Enable Automatic Garbage Collection
package main
import "fmt"
func newValue() *int {
v := 42 // safely escapes to the heap; Go's GC manages its lifetime
return &v
}
func main() {
p := newValue()
fmt.Println(*p)
}
Login to try C/C++/Java/PHP code in the editor
- Confusing & (address-of) with * (dereference) -- & gets a pointer to a value, * gets the value a pointer points to.
- Assuming pointers require manual memory management like in C -- Go's garbage collector handles freeing memory automatically.
- Printing a pointer variable directly and being confused by the hexadecimal memory address instead of dereferencing it first to see the value.
- A pointer holds the memory address of a value, rather than the value itself.
- &x gets the address of x (a pointer); *p gets the value a pointer p points to.
- Go pointers are garbage collected -- there's no manual malloc/free like in C.
- Pointers are used to let a function modify a caller's variable, or to avoid copying large values.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: