1. Error handling — no exceptions
- Functions return errors as a value; check them explicitly.
f, err := os.Open("x.txt")
if err != nil {
log.Fatal(err)
}
errors.New("...")for simple errors; wrap withfmt.Errorf("...: %w", err)to preserve context.errors.Is(err, target)/errors.As(err, &target)for sentinel errors and typed unwrapping.- Prefer an error type (struct implementing
Error() string) when extra info is needed.
2. sync utilities
sync.Mutex
mu.Lock()/mu.Unlock()guard shared state.- Always
defer mu.Unlock()right after locking.
sync.RWMutex
- Multiple readers or one writer;
RLock/RUnlockfor reads,Lock/Unlockfor writes.
sync.WaitGroup
wg.Add(1)/go worker(); wg.Done()/wg.Wait()— the classic “wait for goroutines” pattern.
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(n int) { defer wg.Done(); fmt.Println(n) }(i)
}
wg.Wait()
sync.Once
once.Do(f)runsfexactly once, even across goroutines — lazy init.
atomic
sync/atomicfor lock-free counters:atomic.AddInt64(&n, 1).atomic.Valuefor typed lock-free reads/writes.
3. nil vs empty — the FAQ
| Thing | nil | empty / zero |
|---|---|---|
| slice | var s []int → nil, len 0 | s := []int{} — non-nil, len 0 |
| map | var m map[string]int — read OK, write panics | m := map[...]... |
| string | — | empty string "" |
len/cap/rangeon a nil slice/map is fine; only map writes panic.nilslice ==nilslice;[]int{}==nil? No.s == nilis the common presence check;len(s) == 0is the “empty” check.
4. Gotcha sheet — interview fast-refresh
- Slicing aliases the backing array.
- Ranges copy —
for i, v := range slicecopiesv. - Closure capture:
for i := range xs { go func(){ fmt.Println(i) }() }— with Go < 1.22 all print the last value; the variables are per-loop now but the rule of capturing a copy still applies. - Defer args are evaluated at defer time.
- Struct field tags don’t affect equality.
byte=uint8,rune=int32— aliases.- Zero value used as default — structs start zeroed, no constructor needed.
- Interface holds type + value — the “typed nil” trap.
5. Interview checkpoint
- Error vs panic balance;
errors.Is/As. - Mutex/WaitGroup/atomic when questions get concurrency-y.
- nil vs empty slice/map — the interview favorite.
- Shadowing (
:=vs=) and unused variable errors. go vet,go test,go fmt,go mod tidy— the daily cadence.
Premium Content
Unlock Part 4: Errors, Sync & Top Gotchas and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans