Go - Pointers (Basics)
Beginner 10/10
Teacher 10/10
Architect 10/10
Try it: Create an
int
, take its address with &
, and modify it through the pointer.Addresses and Dereference
x := 10
p := &x // p is *int pointing to x
fmt.Println(*p) // 10
a := *p
*p = 20 // modifies x
When to Use
- To mutate values in called functions.
- To avoid copying large structs.
- For methods requiring pointer receivers.
Common errors
- Returning pointers to locals is okay in Go (escape analysis); avoid when unnecessary.
Practice
- Write a function that increments an
int
via pointer.
Quick quiz
- What’s the zero value of a pointer?
Show answer
nil
.