Stage 1 · Code
Programming Foundations
Pointers
Pointer mechanics, dereferencing, and when to use them in Go.
Pointer Basics
A pointer holds the memory address of a value. In Go, pointers are explicit — no pointer arithmetic, no -> operator. Use & to get address, * to declare pointer type.
Dereferencing and Modification
Dereferencing with * lets you read and modify the underlying value. This is how functions can modify caller's variables.
Pointer vs Value Receivers
Methods can have value or pointer receivers. This affects whether the method can modify the receiver and whether it's called on value or pointer.
| Aspect | Value Receiver | Pointer Receiver |
|---|---|---|
| Syntax | func (v Type) Method() | func (v *Type) Method() |
| Can modify receiver | No (modifies copy) | Yes |
| Called on | Value or pointer | Value or pointer (auto-deref) |
| Copy cost | Copies entire struct | Copies pointer only |
| Concurrency | Safe (owns copy) | Needs synchronization |
When to Use Pointers
- Modify caller's variable: Pass pointer to allow mutation.
- Large structs: Avoid copying big structs (though Go's escape analysis often puts them on heap anyway).
- Consistency: If some methods need pointer receiver, use pointer for all methods of that type.
- Nil semantics: Need to distinguish 'zero value' from 'not set' (e.g.,
*ConfigvsConfig). - Interface implementation: Methods on pointer receiver only satisfy interface when called on pointer.
Go is designed for value semantics. Pass by value for small structs (< ~couple hundred bytes). The compiler optimizes well. Pointers add GC pressure and cognitive overhead. Profile before optimizing.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.