Pointers Cheatsheet
Operators
&variable: Get the memory address (pointer) of a variable.
*pointer: Dereference to get/set the value at that address.
*type: Define a pointer type (e.g., *int, *User).
Common Operations
x := 10
p := &x // Address-of
fmt.Println(*p) // Dereference (10)
*p = 20 // Mutate original
Structs
u := &User{Name: "Bob"}
u.Name = "Alice" // Shorthand for (*u).Name
Receivers
- Value Receiver:
func (u User) ... (Works on a copy)
- Pointer Receiver:
func (u *User) ... (Can modify original)
Key Rules
- Nil Safety: Always check
if p != nil before dereferencing.
- Reference Types: Maps and slices are already reference types (don’t usually need a pointer to them).
- No Arithmetic: You cannot do
p++ in Go.
- Performance: Small values are often faster on the stack than pointers on the heap.