Skip to content

Control Flow: if/else, switch, for, labels, break/continue ​

"There is no do or while loop, only a slightly generalized for; switch is more flexible; if and switch accept an optional initialization statement like that of for;" — Effective Go, section "Control structures"

Summary: Go has three control structures, if, switch and for (plus select and goto), and each is smaller than its C or PHP cousin: no parentheses, no while, no implicit fall-through, and since Go 1.22 a fresh loop variable per iteration. Focus: if with an init statement and guard clauses, expression, tagless, fallthrough and type switch, every for form, every range source (slice, string, map, channel, integer, function), per-iteration loop variables, labels with break/continue/goto, defer in loops, state machines, bounds checks and the classic mistakes. Learning goal: Read any Go loop or branch and say exactly what runs, in what order and with which variable, then write it in the early-return style reviewers expect.

This page owns the statements that decide what runs next. It does not re-teach neighbours: how slices, arrays and maps are laid out is in Arrays, Slices & Maps, interface values and type assertions are in Interfaces, Type Assertions, Type Switches & any, defer, panic and error wrapping are in Errors, Wrapping, Panic, Recover & Defer, closures are in Functions: Multiple Returns, Variadics, Closures, Recursion, Function Types, and select, channels and goroutines are in select: Multiplexing, Non-Blocking Ops, Timeouts, for-select and Goroutines & Channels. Here each of them gets one honest paragraph and a link.

Language facts below come from the Go specification (the copy I read is the "go1.27" revision of 26 May 2026), Effective Go, the Go 1.22, 1.23 and 1.25 release notes and the Go blog posts listed in the references. Go snippets are in a module with go 1.24 in go.mod; all of them pass gofmt, go vet and go test -race.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why Go has so few statementsWhy it exists
Where the rules come from, which Go version added whatWhere it comes from
if err != nil, scoped variables, else after returnif and the init statement and Early return and guard clauses
switch without break, several values per caseExpression switch
switch { case x > 1: }Tagless switch
fallthrough and where it is forbiddenfallthrough
switch v := x.(type)Type switch
for in its three shapesThe for statement
range over slices, strings, maps, channelsrange sources
for i := range 10Range over an integer
iter.Seq, iter.Seq2, iter.PullRange over a function
Closures that all print the last valueLoop variables
break outer, continue outer, gotoLabels, break, continue and goto
defer inside a loopdefer in a loop
What select is, in one pageselect
Random map order, deleting while rangingMaps and range
index out of range, yield panic, vet outputMechanics
Bounds checks, range over big structsPerformance
State machines, time.Tick, fixes in codeSolving the classic problems
Which construct for which situationChoosing
One process to many servicesIn architecture
Run it yourselfLab

Everything in one minute ​

StatementPlain wordsTiny exampleGotcha
ifRun a block when a bool is trueif n < 0 { return }No parentheses, braces mandatory, only bool conditions
if initDeclare a variable that lives only in the if/else chainif v, ok := m[k]; ok {}v and ok are gone after the chain
switchFirst matching case runs, then the switch endsswitch day { case "sat", "sun": }No fall-through unless you write fallthrough
tagless switchA tidy if/else if chainswitch { case n > 9: }Cases are evaluated top to bottom, first true wins
type switchBranch on the dynamic type of an interfaceswitch v := x.(type)fallthrough is not allowed here
forThe only loop keywordfor i := 0; i < n; i++ {}There is no while or do
for condWhile-style loopfor n > 1 {}Infinite if the condition never changes
for {}Infinite loopfor { ... break }Needs a break, return or panic to end
for rangeIterate a collectionfor i, v := range xs {}v is a copy of the element
for range nRepeat n times (Go 1.22)for i := range 3 {}n must be an integer; zero or negative runs zero times
range over funcCustom iterators (Go 1.23)for v := range seq {}The iterator must stop when yield returns false
breakLeave the innermost for, switch or selectbreakInside a switch it does NOT leave the surrounding loop
continueNext iteration of the innermost forcontinueNot valid in switch outside a loop
labelA name for the statement it precedesouter: for {}An unused label is a compile error
gotoJump to a label in the same functiongoto cleanupCannot jump over a variable declaration or into a block
Go versionWhat changed for control flowWhere
1.0if, switch, for, range, labels, goto, selectspec
1.22Per-iteration loop variables; range over integersLoop variables, Range over an integer
1.23Range over functions; iter package; time.Tick garbage-collectableRange over a function, Ticker leaks
1.24testing.B.Loop replaces for i := 0; i < b.N; i++ in benchmarksPerformance
1.25Release notes: nothing in the statements themselves; semantics unchangedMechanics
MistakeSymptomSection
Closure captures loop variable on go.mod below 1.22Every goroutine sees the last valueLoop variables
Modify the range copySlice does not changerange copies values
Rely on map orderFlaky tests, unstable JSONMaps and range
break inside switch inside forLoop keeps runningLabels
defer in a long loopMemory and file descriptors pile up until returndefer in a loop
for with no yield100% CPU, other work starvesInfinite loops
time.Tick in old modulesTicker never freedTicker leaks

Why it exists ​

Control flow is where programs spend their bugs. C-family languages accumulated many ways to loop and branch (while, do ... while, foreach, implicit fall-through, comma operators) and each had its own trap. Go's authors chose to remove choices: one loop keyword, one switch, braces always required, no ternary operator. The FAQ's answer on the missing ?: operator ends with the same idea: "A language needs only one conditional control flow construct." The effect is that code written by different people looks the same.

Language choiceWhat you give upWhat you get
One loop keyword forwhile, do-while, foreach spellingOne thing to learn; every loop has the same layout
Braces always, no parenthesesBrace-less one-linersNo "goto fail" style bug, shorter conditions
switch breaks by defaultConcise fall-through tricksThe common case is the safe case
if/switch init statementDeclaring variables above the statementSmaller scope, fewer leaked names
Per-iteration loop variablesC-style "one shared counter" mental modelClosures and goroutines behave as written
No exceptions, errors are valuesShort try/catch blocksError handling is plain if, so it is visible control flow

Everyday picture: a road map. if is a fork with two roads; switch is a roundabout with many exits where you never drive on into the next exit by accident; for is a ring road you drive until you decide to leave; a label is a named exit you can take from deep inside several nested roundabouts.

Three common misunderstandings, up front ​

  1. "switch needs break like in C or PHP." It does not; the first matching case runs and the switch ends. The mistake goes the other way: a break inside a switch inside a for leaves only the switch.
  2. "The loop variable is one variable that changes." That was true until Go 1.22. With go 1.22 or later in go.mod every iteration has its own copy, which silently fixes a famous bug and silently changes the meaning of old code if you raise the version.
  3. "range gives me the element." It gives you a copy of the element; to change the slice write through the index.

Where it comes from ​

Go's statements are inherited from C and Pascal with deliberate cuts; Effective Go is the earliest readable statement of the style ("Control structures"), and the spec is the contract. Three later changes matter for this page, all documented in release notes:

ChangeReleasePrimary source
"For" loops may range over integersGo 1.22go.dev/doc/go1.22
Loop variables created anew for each iteration (gated on the go line in go.mod)Go 1.22go.dev/doc/go1.22, go.dev/blog/loopvar-preview
iter package and range-over-funcGo 1.23go.dev/doc/go1.23, go.dev/blog/range-functions
Unreferenced Timers and Tickers are collectable; timer channels unbufferedGo 1.23 (module must say go 1.23 or later)go.dev/doc/go1.23

The loop-variable change is the only time Go deliberately changed the meaning of existing syntax. It was rolled out as an experiment (GOEXPERIMENT=loopvar), tested against Google's own code, and shipped per module: a module whose go.mod says go 1.21 keeps the old behaviour even when built with a newer toolchain. That gate is the reason every sentence about loop variables on this page says "go.mod".

The concept catalogue ​

if and the init statement Must-know ​

In plain words: if runs a block when a condition is true. You may put one short statement before the condition; variables it declares exist only inside the if and its else branches.

Common misunderstanding: "Go lets me write if x for any value, like PHP's truthiness." The condition must be of type bool. if n {} with an int does not compile, and there is no truthy string or empty array.

Definition: if [SimpleStmt ;] Expression Block [else (if | Block)]. The braces are mandatory and the opening brace must be on the same line.

step  code                                  scope of v, ok
1     if v, ok := m[k]; ok {                v, ok declared
2         use(v)                            visible
3     } else if v > 10 {                    still visible (same chain)
4         ...                               visible
5     }                                     gone
6     use(v)                                compile error: undefined: v

Real scenarios: the comma-ok map lookup; if err := os.Remove(p); err != nil; parsing a header once (if n, err := strconv.Atoi(h); err == nil && n > 0); acquiring a lock and checking a flag in one statement; checking a context error.

Languageif condition typeParenthesesBrace-less bodyInit statement
Gobool onlynot usednot allowedyes
PHPany value (truthiness)requiredallowedno
Cany scalarrequiredallowedno (C99 has it in for only)
Rustbool onlynot usednot allowedno (if let instead)
Javaboolean onlyrequiredallowedno

Fix / how to use it: keep init statements short; if the line gets long, declare the variable on its own line above.

go
if v, ok := m[k]; ok {
	return "found " + strconv.Itoa(v)
}
return "missing"

The full runnable file with tests:

go
// Package branching shows guard clauses, if with an init statement and the
// three switch shapes: expression, tagless and fallthrough.
package branching

import (
	"errors"
	"strconv"
)

var ErrNegative = errors.New("negative quantity")

// ParseQty uses guard clauses: every failure returns early, the happy path
// stays at the left margin.
func ParseQty(s string) (int, error) {
	n, err := strconv.Atoi(s)
	if err != nil {
		return 0, err
	}
	if n < 0 {
		return 0, ErrNegative
	}
	if n > 1000 {
		n = 1000
	}
	return n, nil
}

// ParseQtyNested is the same logic with else chains (what reviewers flag).
func ParseQtyNested(s string) (int, error) {
	if n, err := strconv.Atoi(s); err != nil {
		return 0, err
	} else {
		if n < 0 {
			return 0, ErrNegative
		} else {
			if n > 1000 {
				n = 1000
			}
			return n, nil
		}
	}
}

// Lookup scopes v and ok to the if statement only.
func Lookup(m map[string]int, k string) string {
	if v, ok := m[k]; ok {
		return "found " + strconv.Itoa(v)
	}
	return "missing"
}

// Kind uses an expression switch: cases do not fall through, a case may list
// several values.
func Kind(day string) string {
	switch day {
	case "sat", "sun":
		return "weekend"
	case "mon", "tue", "wed", "thu", "fri":
		return "weekday"
	default:
		return "unknown"
	}
}

// Grade is a tagless switch: each case is a boolean, the first true one wins.
func Grade(score int) string {
	switch {
	case score >= 90:
		return "A"
	case score >= 80:
		return "B"
	case score >= 0:
		return "C"
	default:
		return "invalid"
	}
}

// Perms shows fallthrough: it runs the next case body without testing it.
func Perms(level int) []string {
	var out []string
	switch level {
	case 3:
		out = append(out, "delete")
		fallthrough
	case 2:
		out = append(out, "write")
		fallthrough
	case 1:
		out = append(out, "read")
	}
	return out
}

Early return and guard clauses Must-know ​

In plain words: handle the unhappy case first and leave the function. The normal path ("happy path") then runs straight down the left margin without else.

Common misunderstanding: "else after a return is more explicit." It adds indentation without adding information; the Go code review comments call this "Indent Error Flow" and ask for the opposite.

Definition: a guard clause is an if whose body ends with return, continue, break or panic, placed before the main logic. The Go wiki on code review comments says to keep the normal code path at minimal indentation and deal with errors first.

nested style                          guard style
1 if err == nil {                     1 if err != nil { return err }
2     if ok {                         2 if !ok { return ErrNotOK }
3         if n > 0 {                  3 if n <= 0 { return ErrEmpty }
4             work()                  4 work()
5         }                           
6     }
7 }

Real scenarios: HTTP handlers (validate, then act), repository methods (sql.ErrNoRows first), message consumers that continue on a malformed record, permission checks at the top of a service method.

StyleIndent depth for 3 checksWhere the happy path livesReviewer reaction
Guard clauses1Bottom, unindentedPreferred
else chains after return3Innermost blockFlagged
Single exit with result variable1-2AnywhereAccepted for cleanup-heavy code

The ParseQty and ParseQtyNested functions in the file above are the same logic in both styles; the tests run both against the same cases.

Expression switch Must-know ​

In plain words: compare one value against several candidates and run the first body that matches. A case can list many values separated by commas.

Common misunderstanding: "I need break at the end of each case." You do not. Conversely "break leaves my loop" is false inside a switch: it only ends the switch (see Labels).

Definition: switch [init;] [tag] { case expr-list: ... default: ... }. Cases are evaluated left to right and top to bottom; the first match runs; default may appear anywhere and runs only when nothing else matched. Case expressions need not be constants. Duplicate constant cases are a compile error.

step  switch day {            day = "sun"
1     case "sat", "sun":      compare "sun" with "sat" -> no, "sun" -> yes
2         return "weekend"    run, then leave the switch
3     case "mon", ...         never compared
4     default:                skipped

Real scenarios: HTTP method dispatch, parsing a command-line subcommand, mapping an error code to a status, picking a codec from a content type, runtime.GOOS specific code.

FeatureGo switchPHP switchPHP matchC switch
Fall-through by defaultNoYesNoYes
Comparison== on the tag, any comparable typeloose ==strict ===integer constants only
Non-constant casesYesYesYesNo
Returns a valueNo (statement)NoYes (expression)No
Missing casesilently nothingsilently nothingUnhandledMatchErrorsilently nothing

Tagless switch Must-know ​

In plain words: switch with no value is a readable replacement for a long if/else if chain; each case is a boolean.

Common misunderstanding: "Without a tag it compares against true only for the first case." Every case is a boolean expression, tested in order; the first true wins.

Definition: switch { case a > 1: ... } is the same as switch true { ... }.

step  switch {                score = 85
1     case score >= 90:       false
2     case score >= 80:       true -> run, leave
3     case score >= 0:        not evaluated

Real scenarios: grading and tiering, rate-limit decisions, picking a retry delay by attempt count, classifying HTTP status ranges (code >= 500).

Order matters: put the narrowest condition first. A score >= 0 placed first would shadow the others and go vet will not warn you.

fallthrough Important ​

In plain words: fallthrough runs the next case's body without testing its condition. It is rare.

Common misunderstanding: "fallthrough re-checks the next case." It does not; it transfers control unconditionally to the first statement of the next clause.

Definition: the spec says fallthrough may appear only as the last non-empty statement of a case clause that is not the last clause, and "The fallthrough statement is not permitted in a type switch."

1  Perms(3):  case 3 -> append "delete"
2             fallthrough -> body of case 2 runs without testing
3             append "write", fallthrough
4             append "read"
5  result: [delete write read]

Real scenarios: cumulative permission levels, rendering a decreasing-detail log message, parsing legacy fixed formats. In most code a list of values (case 1, 2, 3:) is what you wanted.

Type switch Important ​

In plain words: branch on what concrete type is inside an interface value. In a case with a single type, the new variable has that type.

Common misunderstanding: "A type switch works on any variable." The tag must be an interface value; x.(type) is only legal inside the switch header.

Definition: switch v := x.(type) { case int: ... case string, []byte: ... case nil: ... default: ... }. With several types in one case, v keeps the interface type. This page does not teach interfaces; see Interfaces, Type Assertions, Type Switches & any.

go
switch v := x.(type) {
case int:
	return v + 1 // v is int
case error:
	return v.Error() // v is error
default:
	return fmt.Sprintf("%T", v) // v is any
}

Real scenarios: decoding any from encoding/json, handling several error types, visiting an AST.

The for statement Must-know ​

In plain words: for is Go's only loop. It has three shapes: classic (init; condition; post), condition-only (a while), and bare (infinite).

Common misunderstanding: "Go must have a while somewhere." It does not; for cond {} is it.

Definition (spec): for cond { S() } is the same as for ; cond ; { S() } and for { S() } is the same as for true { S() }.

step  for i := 0; i < 3; i++ { body }
1     init: i = 0
2     test i < 3 -> true, run body
3     post: i++ -> 1
4     test -> true, run body
5     ... until the test is false, then leave
FormSpellingTypical use
Classicfor i := 0; i < n; i++Index math, counting down, two indexes
Conditionfor n > 1Until a value converges, drain a buffer
Infinitefor { }Servers, select loops, retry with break
Rangefor i, v := range xCollections, channels, iterators
Range, no variablesfor range ch or for range 3Run n times; wait for a channel to close

Infinite loops without a yield point ​

An infinite for {} that does not block (no channel operation, no I/O, no time.Sleep, no function call that can yield) spins one CPU core at 100%. Since Go 1.14 the scheduler can preempt it, so other goroutines still run, but the core is burned. Always put a blocking call, a select or a context check in the body, or sleep with a timer.

1  for { if ready() { break } }            spins, burns a core
2  for { select { case <-ctx.Done(): return; case job := <-jobs: work(job) } }   blocks while idle
go
// Package loops shows every for form and the range sources.
package loops

import (
	"slices"
	"sort"
)

// Classic is the three-clause form.
func Classic(n int) []int {
	var out []int
	for i := 0; i < n; i++ {
		out = append(out, i)
	}
	return out
}

// Condition is the while-style form.
func Condition(n int) int {
	steps := 0
	for n > 1 {
		if n%2 == 0 {
			n /= 2
		} else {
			n = 3*n + 1
		}
		steps++
	}
	return steps
}

// Infinite loops until the break; the only exits are break and return.
func Infinite(limit int) int {
	i := 0
	for {
		i++
		if i*i > limit {
			break
		}
	}
	return i
}

// RangeInt is range over an integer (Go 1.22): 0..n-1.
func RangeInt(n int) []int {
	var out []int
	for i := range n {
		out = append(out, i)
	}
	return out
}

// Runes ranges over a string: index is the BYTE offset, value is a rune.
func Runes(s string) (idx []int, runes []rune) {
	for i, r := range s {
		idx = append(idx, i)
		runes = append(runes, r)
	}
	return
}

// SortedKeys makes map iteration deterministic by sorting the keys.
func SortedKeys(m map[string]int) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}

// SortedKeys2 does the same with the 1.23 iterator helpers.
func SortedKeys2(m map[string]int) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	slices.Sort(keys)
	return keys
}

type Item struct{ N int }

// DoubleCopy forgets that the range value is a copy: items never change.
func DoubleCopy(items []Item) {
	for _, it := range items {
		it.N *= 2
	}
}

// DoubleIndex writes through the index and does change the slice.
func DoubleIndex(items []Item) {
	for i := range items {
		items[i].N *= 2
	}
}

// Drain ranges over a channel until it is closed.
func Drain(ch <-chan int) (sum int) {
	for v := range ch {
		sum += v
	}
	return
}

// PruneEven deletes during range: allowed, entries not yet reached vanish.
func PruneEven(m map[int]bool) {
	for k := range m {
		if k%2 == 0 {
			delete(m, k)
		}
	}
}

// RangeLenOnce shows the range expression is evaluated once: appending
// inside the loop does not extend it.
func RangeLenOnce(s []int) int {
	iterations := 0
	for range s {
		s = append(s, 0)
		iterations++
	}
	return iterations
}

range sources Must-know ​

In plain words: range walks a collection and hands you one or two values per step. What those values are depends on the thing you range over.

Common misunderstanding: "for i, c := range str gives bytes, and i counts characters." For a string, i is the byte offset and c is a rune decoded from UTF-8; the offsets skip by the rune's byte length.

Definition: the range expression is evaluated once before the loop starts.

Range overFirst valueSecond valueNotes
array, slice, pointer to arrayindexcopy of elementlength fixed at loop start for slices (the slice header is copied)
stringbyte index of the runerune (int32)invalid UTF-8 yields U+FFFD and advances one byte
mapkeyvalueorder is unspecified and varies run to run
channelelementnoneruns until the channel is closed; nil channel blocks forever
integer n0 .. n-1noneGo 1.22; n of zero or less runs zero times
func(yield func() bool)nonenoneGo 1.23
func(yield func(V) bool)Vnoneiter.Seq[V]
func(yield func(K, V) bool)KViter.Seq2[K, V]
1  s := "aé世"                       bytes: 61 | c3 a9 | e4 b8 96
2  for i, r := range s               i=0 r='a' ; i=1 r='é' ; i=3 r='世'
3  len(s) = 6, utf8.RuneCountInString(s) = 3

Real scenarios: counting characters, validating names, draining a worker channel, walking config maps in sorted order for stable output.

for (one keyword)for i := 0; i < n; i++for cond { }for { } (break/return)for range ...for i := range 10for v := range seqno while, no do-whilerange source : yieldsslice / array : index, copy of elementstring : byte offset, rune (UTF-8)map : key, value (order random)channel : values until closeinteger n : 0 .. n-1 (Go 1.22)func(yield) : whatever yield gets (1.23)range expression evaluated once

range copies values ​

for _, it := range items { it.N *= 2 } changes a copy and the slice stays as it was. Write for i := range items { items[i].N *= 2 } or range over a slice of pointers. The test TestCopyAndChannel in the snippet proves both. The same applies to arrays: ranging over an array value first copies the whole array (range over &arr or a slice to avoid it).

The range expression is evaluated once ​

Appending to a slice while ranging over it does not extend the loop: RangeLenOnce in the snippet runs exactly len(s) iterations even though it appends each time.

Range over an integer Must-know ​

In plain words: for i := range 10 runs ten times with i from 0 to 9.

Common misunderstanding: "It works on any number." It needs an integer type (untyped constants default to int); floats do not work. Ranging over zero or a negative value does nothing, no error.

Definition: Go 1.22 release notes: "For" loops may now range over integers. The type of i follows the type of the range expression.

1  for i := range 3 { f(i) }     f(0) f(1) f(2)
2  for range 3 { g() }           g() three times, no variable
3  n := -5; for range n { }      zero iterations

Real scenarios: retry attempts (for attempt := range maxAttempts), spawning N workers, benchmarks, table generation.

SpellingMeaningNeed Go
for i := 0; i < n; i++classicany
for i := range nsame, shorter1.22
for range nn times, no variable1.22
for i := n - 1; i >= 0; i--downward; no range equivalentany

Range over a function Important ​

In plain words: you can range over a function that calls your loop body for each value. Standard library collections expose these as iterators.

Common misunderstanding: "The iterator is a goroutine or a channel." It is plain function calls; the loop body is passed to the iterator as the yield function and runs on the same goroutine.

Definition: iter.Seq[V] is func(yield func(V) bool) and iter.Seq2[K, V] is func(yield func(K, V) bool). If the loop body executes break, return or goto out of the loop, yield returns false and the iterator must return promptly. A function that keeps calling yield after a false result panics at run time.

1  for v := range Count(1000000) { if v > 3 { break } }
2  Count calls yield(0) true, yield(1) true, yield(2) true, yield(3) true
3  yield(4) -> body executes break -> yield returns false
4  Count sees false and returns; 5 values produced of 1,000,000 possible
for v := range seq { body }body becomes yield(v) boolreturns true : keep goingbreak / return : falsecontinue : trueiterator func(yield)for ... { if !yield(x) { return } }must stop after falseignoring false: runtime paniciter.Seq[V] / iter.Seq2[K,V]callyield(x)

Real scenarios: slices.Values, maps.Keys and slices.Sorted(maps.Keys(m)) for ordered map walks; paginated database cursors exposed as iterators; walking a tree without allocating a slice; streaming lines from a reader; iter.Pull to turn a push iterator into a next()/stop() pair (needed for zipping two sequences).

TypeShapeProducer examples
iter.Seq[V]one value per stepslices.Values, maps.Keys, your own generators
iter.Seq2[K, V]two values per stepslices.All, maps.All
iter.Pullpull style: next() and stop()zipping two sequences, merging
channelgoroutine to goroutinewhen producer and consumer must run concurrently

Choose an iterator over a channel when the producer and consumer are in the same goroutine: no goroutine to leak, no buffer, early break is free. Choose a channel for real concurrency.

go
// Package iterators shows range-over-func (Go 1.23): iter.Seq, iter.Seq2,
// early exit through the yield result and iter.Pull.
package iterators

import (
	"iter"
	"maps"
	"slices"
)

// Count yields 0..n-1.
func Count(n int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for i := range n {
			if !yield(i) {
				return // the loop body executed break or return
			}
		}
	}
}

// Filter wraps another sequence lazily.
func Filter[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
	return func(yield func(T) bool) {
		for v := range seq {
			if keep(v) && !yield(v) {
				return
			}
		}
	}
}

// Enumerate yields index/value pairs (iter.Seq2).
func Enumerate[T any](xs []T) iter.Seq2[int, T] {
	return func(yield func(int, T) bool) {
		for i, x := range xs {
			if !yield(i, x) {
				return
			}
		}
	}
}

// FirstOver returns the first value above limit and how many values the
// iterator actually produced: laziness plus early exit.
func FirstOver(seq iter.Seq[int], limit int) (val, produced int) {
	for v := range seq {
		produced++
		if v > limit {
			return v, produced
		}
	}
	return -1, produced
}

// Zip pairs two sequences using iter.Pull for the second one.
func Zip[A, B any](a iter.Seq[A], b iter.Seq[B]) iter.Seq2[A, B] {
	return func(yield func(A, B) bool) {
		next, stop := iter.Pull(b)
		defer stop()
		for x := range a {
			y, ok := next()
			if !ok || !yield(x, y) {
				return
			}
		}
	}
}

// SortedMap iterates a map in key order using maps.Keys and slices.Sorted.
func SortedMap(m map[string]int) []string {
	var out []string
	for _, k := range slices.Sorted(maps.Keys(m)) {
		out = append(out, k)
	}
	return out
}

Loop variables: per-iteration since Go 1.22 Must-know ​

In plain words: before Go 1.22 the variable i of for i := 0; ... was one variable for the whole loop, so closures and goroutines started inside the loop all saw its final value. Since 1.22, each iteration gets its own i.

Common misunderstanding: "The fix applies whenever I use Go 1.22." It applies per module: the go line in go.mod must be 1.22 or higher. The release notes tell you to expect the new semantics only when the module declares it.

Definition (spec): "Each iteration has its own separate declared variable (or variables) [Go 1.22]. The variable used by the first iteration is declared by the init statement. The variable used by each subsequent iteration is declared implicitly before executing the post statement and initialized to the value of the previous iteration's variable at that moment."

go.mod below 1.22                         go.mod 1.22 or later
1  i = 0; closure A captures &i           i#1 = 0; closure A captures i#1
2  i++ (same variable) -> 1; B captures   i#2 = copy of i#1, then ++ -> 1; B captures i#2
3  i++ -> 2; C captures                   i#3 ... C captures i#3
4  i++ -> 3, loop ends                    loop ends
5  A(), B(), C() print 3, 3, 3            A(), B(), C() print 0, 1, 2
go.mod below 1.22i (one slot)closure 1, 2, 3 all point hereloop ends with i = 3calls print 3, 3, 3goroutines saw the last valuego.mod 1.22 or lateri = 0i = 1i = 2each closure owns its slotnew i copied from previousbefore the post statementcalls print 0, 1, 2

Real scenarios: go func() { process(item) }() inside a loop; t.Run(name, func(t *testing.T) { t.Parallel(); use(tc) }) table tests; storing &v of a range variable in a slice (before 1.22 every pointer was the same); registering callbacks in a loop.

Patterngo.mod below 1.22go.mod 1.22 or later
closure over i in classic forall see the final valueeach sees its own
&v stored from rangeall pointers equaldistinct pointers
v := v copy at top of bodyneededredundant, harmless
go func(v T) { ... }(v) argumentworksworks
modifying i inside the bodyaffects the one variablecarried into the next iteration's copy

The old workaround item := item is now noise; remove it only after the module's go line is raised and tests pass. The Go blog's loopvar post and the wiki page "LoopvarExperiment" describe the bisect tool for finding the one loop whose behaviour depends on the change.

go
// Package loopvar demonstrates per-iteration loop variables (Go 1.22) and
// the shared-variable bug they fixed.
package loopvar

// Capture collects closures over the loop variable. With go 1.22+ in go.mod
// each iteration has its own i, so calling them yields 0,1,2.
func Capture() []int {
	var fns []func() int
	for i := 0; i < 3; i++ {
		fns = append(fns, func() int { return i })
	}
	return call(fns)
}

// CaptureShared reproduces the pre-1.22 behaviour explicitly: one variable
// declared outside the loop is shared by every closure, so all see 3.
func CaptureShared() []int {
	var fns []func() int
	var i int
	for i = 0; i < 3; i++ {
		fns = append(fns, func() int { return i })
	}
	return call(fns)
}

// CapturePointers keeps &v of a range variable. Since 1.22 the addresses
// differ; before 1.22 they were all the same address.
func CapturePointers(xs []string) []*string {
	var ps []*string
	for _, v := range xs {
		ps = append(ps, &v)
	}
	return ps
}

// PostStatement shows the copy-forward rule: the body may modify i and the
// change is carried into the next iteration's fresh variable.
func PostStatement() []int {
	var seen []int
	for i := 0; i < 6; i++ {
		seen = append(seen, i)
		if i == 1 {
			i += 2 // skip 2 and 3
		}
	}
	return seen
}

func call(fns []func() int) []int {
	out := make([]int, 0, len(fns))
	for _, f := range fns {
		out = append(out, f())
	}
	return out
}

Labels, break, continue and goto Important ​

In plain words: break and continue act on the innermost loop. A label lets you name an outer statement and act on it from inside.

Common misunderstanding: "break inside a switch stops the loop." It stops the switch (or select); to stop the loop write break loop with a label on the for.

Definition: a label is Name: in front of a for, switch or select. break Name terminates that statement; continue Name starts the next iteration of that for. goto Name jumps to a label in the same function and may not jump over variable declarations or into another block. Declared but unused labels are compile errors (label outer defined and not used).

1  outer: for _, row := range grid {
2      for _, v := range row {
3          if v == want { found = true; break outer }     leaves BOTH loops
4          if v < 0     { continue outer }                skips the rest of this row
5      }
6  }
7  after both loops
outer: for each rowfor each value in rowif v < 0 : continue rowsif v == want : break outerif v == 0 : break (inner only)if v == 1 : continue (inner only)after inner loop: next rowafter outer loop: code after the loopsWhere control goesbreak : leaves innermost for, switch or selectcontinue : next iteration of innermost forbreak L / continue L : the enclosing statement named Lgoto L : same function only

Real scenarios: searching a 2-D grid, a for/select loop that must leave on a "quit" case (break loop), batch processors that abandon a whole batch on one bad record (continue batch), retry loops with an inner reader loop.

StatementTargetValid inside
breakinnermost for, switch, selectthose three
continueinnermost forfor (also nested in switch)
break Lenclosing statement labeled Lfor, switch, select
continue Lenclosing for labeled Lfor only
goto Lany label in the same functionanywhere, with the scope rules

goto ​

goto is legal and rare. Go code uses it in generated parsers and for one shared cleanup path in functions that cannot use defer. Rules from the spec: executing goto must not cause any variable to come into scope that was not already in scope at the point of the goto, and a goto outside a block cannot jump into that block. For ordinary cleanup prefer defer.

go
// Package labels shows labeled break/continue, plain break inside switch and
// goto for cleanup.
package labels

import "errors"

// FindPair returns the first (i, j) with grid[i][j] == want. The label lets
// the inner loop stop the outer one.
func FindPair(grid [][]int, want int) (int, int, bool) {
	ri, rj, found := -1, -1, false
outer:
	for i, row := range grid {
		for j, v := range row {
			if v == want {
				ri, rj, found = i, j, true
				break outer
			}
		}
	}
	return ri, rj, found
}

// SkipRows counts values, skipping any row that contains a negative number.
func SkipRows(grid [][]int) int {
	total := 0
rows:
	for _, row := range grid {
		for _, v := range row {
			if v < 0 {
				continue rows
			}
		}
		total += len(row)
	}
	return total
}

// BreakInSwitch: a bare break inside switch leaves only the switch.
func BreakInSwitch(xs []string) int {
	n := 0
	for _, x := range xs {
		switch x {
		case "stop":
			break // leaves the switch, not the loop
		default:
			n++
		}
	}
	return n
}

// StopOnLabel uses a label so break leaves the for from inside the switch.
func StopOnLabel(xs []string) int {
	n := 0
loop:
	for _, x := range xs {
		switch x {
		case "stop":
			break loop
		default:
			n++
		}
	}
	return n
}

var errBad = errors.New("bad step")

// Run uses goto to share one cleanup path; the jump does not skip any
// variable declaration, which the spec forbids.
func Run(steps []bool) (cleaned bool, err error) {
	for _, ok := range steps {
		if !ok {
			err = errBad
			goto cleanup
		}
	}
	return false, nil
cleanup:
	cleaned = true
	return cleaned, err
}

defer in a loop Important ​

In plain words: a defer runs when the surrounding function returns, not when the loop iteration ends. In a loop over a thousand files, a thousand files stay open until the function exits.

Common misunderstanding: "defer f.Close() in the loop body closes the file at the end of each iteration." It does not; deferred calls queue up and run in last-in-first-out order when the function returns.

Definition: each defer statement pushes a call on the function's defer stack; the stack unwinds on return or panic. The details and recover are in Errors, Wrapping, Panic, Recover & Defer.

1  for _, p := range paths { f, _ := os.Open(p); defer f.Close() }
2  iteration 1: open A, push Close(A)
3  iteration 2: open B, push Close(B)
4  ... 10,000 files open at once -> "too many open files"
5  function returns: Close(B) then Close(A) (LIFO)

Fix: wrap the loop body in a function (func() { ...; defer f.Close() }()), or call Close explicitly, or extract a helper such as processFile(path) error.

ApproachFiles open at onceCloses on panicCost
defer in the loop bodyall of themyes, at function returnmemory and descriptors
helper function with deferoneyesone call per item
explicit Close after useonenoforgotten on early return

select Good to know ​

In plain words: select is switch for channel operations: it waits until one of several sends or receives can proceed. It has its own page, select: Multiplexing, Non-Blocking Ops, Timeouts, for-select.

Common misunderstanding: "select picks the first ready case in source order." When several are ready, one is chosen pseudo-randomly. A break inside a select leaves the select, exactly like in switch; a for { select { ... } } loop therefore needs a label or a return to end.

Definition: select { case v := <-ch: ... case ch2 <- x: ... default: ... }. With default the statement never blocks.

1  loop:
2  for {
3      select {
4      case job := <-jobs: handle(job)
5      case <-ctx.Done():  break loop
6      }
7  }

Maps and range Must-know ​

In plain words: a map's iteration order is deliberately not stable, and you may delete entries while ranging.

Common misunderstanding: "Small maps iterate in insertion order, and the order I saw is the order I will always get." The spec says order is unspecified and "not guaranteed to be the same from one iteration to the next"; the runtime randomises the starting point, so a test can pass a hundred times and fail on the hundred and first.

Definition (spec): if a map entry not yet reached is removed during iteration it will not be produced; if an entry is created during iteration it may be produced or skipped; ranging over a nil map runs zero times.

1  m = {a,b,c,d,e}
2  run 1: b c d e a        (real output, Go 1.27 host)
3  run 2: a b c d e
4  run 3: b c d e a

Real scenarios: JSON output that must be stable (sort the keys), cache eviction loops (delete while ranging is safe), flaky unit tests comparing printed maps, metrics rendered in random order.

Operation during range mAllowedResult
delete(m, k)yesan unreached deleted key is not produced
m[newKey] = vyesmay or may not be visited
m[existing] = v2yeslater visit sees the new value
concurrent write from another goroutinenofatal error: concurrent map iteration and map write
clear(m)yes (Go 1.21)remaining entries not produced
go
// Command maporder prints a map twice to show that range order is random.
package main

import "fmt"

func main() {
	m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
	for run := 1; run <= 3; run++ {
		fmt.Print("run ", run, ":")
		for k := range m {
			fmt.Print(" ", k)
		}
		fmt.Println()
	}
}

Ticker leaks: time.Tick in a loop Important ​

In plain words: time.Tick(d) returns a channel and no handle to stop it. Before Go 1.23 that ticker lived forever.

Common misunderstanding: "Since 1.23 timers never leak." Go 1.23 made unreferenced Timers and Tickers eligible for garbage collection even without Stop, but "These new behaviors are only enabled when the main Go program is in a module with a go.mod go line using Go 1.23.0 or later." A module on go 1.22 still has the old leak, and holding a ticker that is still referenced (a running for range loop) still keeps it running.

Definition: time.NewTicker(d) gives you t.C and t.Stop(); use defer t.Stop().

1  func poll() { for range time.Tick(time.Second) { check() } }
2  caller stops caring (returns) but poll() never returns: goroutine + ticker leak
3  with NewTicker + select on ctx.Done(): return -> defer t.Stop() releases it

Real scenarios: health-check pollers, metric flushers, leader-lease renewals, cache refreshers started with go poll() and never cancelled.

go
// Package ticker contrasts time.Tick with time.NewTicker + Stop.
package ticker

import (
	"context"
	"time"
)

// CountTicks counts ticks until ctx ends. The ticker is stopped explicitly,
// which is required before Go 1.23 and still the clearest style.
func CountTicks(ctx context.Context, every time.Duration) int {
	t := time.NewTicker(every)
	defer t.Stop()
	n := 0
	for {
		select {
		case <-t.C:
			n++
		case <-ctx.Done():
			return n
		}
	}
}

// Leaky uses time.Tick: there is no handle, so Stop cannot be called. With
// a go.mod below go 1.23 the underlying Ticker is never collected.
func Leaky(ctx context.Context, every time.Duration) int {
	n := 0
	for range time.Tick(every) {
		n++
		if ctx.Err() != nil {
			return n
		}
	}
	return n
}

Mechanics ​

Error texts you will see Must-know ​

TextMeaningFix
panic: runtime error: index out of range [3] with length 3indexing a slice or array past its length at run timecheck the length, range over the slice
panic: runtime error: slice bounds out of range [:5] with capacity 3slicing beyond capacityvalidate bounds
panic: runtime error: range function continued iteration after function for loop body returned falsean iterator ignored yield returning falsereturn when yield is false
fatal error: concurrent map iteration and map writemap written while another goroutine rangesguard with a mutex or copy keys first
fatal error: concurrent map writestwo goroutines wrote one mapmutex or sync.Map
fatal error: all goroutines are asleep - deadlock!every goroutine blocked, for example range ch over a channel nobody closesclose the channel, see Goroutines & Channels
label outer defined and not usedcompile error: label never targetedremove it or use it
goto L jumps over declaration of x at ./main.go:14:4compile error: jump skips a declarationmove the declaration before the goto
cannot fallthrough final case in switchfallthrough in the last clauseremove it
non-boolean condition in if statementnon-bool conditionwrite the comparison
cannot range over 3.5 (untyped float constant)range needs a rangeable typeuse an integer, slice, string, map, channel or function
duplicate case 1 (constant of type int) in expression switchthe same constant twiceremove one
unreachable code (vet)statements after return, panic, infinite fordelete or restructure
loopclosure (vet)loop variable captured by go/defer closure in older modulesraise go line or copy

Version gates, in one table Must-know ​

FeatureNeeds go lineWhat happens below
for i := range 101.22compile error: cannot range over 3 (untyped int constant): requires go1.22 or later (-lang was set to go1.21; check go.mod)
per-iteration loop variables1.22one shared variable
for v := range seq (functions)1.23compile error: cannot range over function (needs go1.23)
iter, maps.Keys, slices.Sorted1.23package or symbol missing
collectable Ticker/Timer, unbuffered timer channels1.23old buffered, never-collected behaviour
testing.B.Loop1.24not defined
clear on maps and slices1.21undefined: clear

Evaluation order inside the statements ​

1  for i := 0; i < len(s); i++   len(s) is re-evaluated every iteration
2  for i := range s              s is evaluated once; len fixed at that moment
3  switch f() { case g(): ...}   f() once; g() only until a case matches
4  if a() && b()                 b() runs only when a() is true (short circuit)

Bounds checks ​

Every s[i] is checked against len(s) at run time and panics with the index out of range text when it fails. The compiler removes the check when it can prove it safe. You can ask it which checks remain with go build -gcflags=-d=ssa/check_bce/debug=1. The real output for the bce snippet (Go 1.27 toolchain on the host) is:

bce/bce.go:7:9: Found IsInBounds     (Classic: s[i] with i < n, nothing proves n <= len(s))
bce/bce.go:21:7: Found IsInBounds    (Hint: the single check is `_ = s[3]`; the next three loads need none)

Range (for i := range s) produced no line: the compiler knows i < len(s). Two practical rules follow. Prefer range over indexing against a separate length, and when you must read s[0]..s[3] do one early _ = s[3] so the panic happens once at the top.

Range over big structs ​

for _, v := range xs copies each element into v. For large structs the index form xs[i] avoids the copy in principle. I measured it (Go 1.27, rangecost snippet, 1000 elements of 2 KB, Apple silicon laptop, single run, not a statistically controlled benchmark):

BenchmarkValue-12      4792224     246.0 ns/op
BenchmarkIndex-12      3838761     310.2 ns/op

The value form was not slower, because the compiler recognises that v is only read for v.ID and does not copy the whole struct. Do not assume either direction: write the clear form, measure with a benchmark, and switch only when profiling points at the loop. A correctness reason to use the index (you must modify the element) is stronger than the performance reason.

go
// Package rangecost compares range forms over a slice of large structs.
package rangecost

type Big struct {
	ID   int
	Data [256]int64
}

// SumValue copies every element into v (the compiler may elide some copies,
// but you cannot rely on it for big structs).
func SumValue(xs []Big) (s int) {
	for _, v := range xs {
		s += v.ID
	}
	return
}

// SumIndex reads through the index: no element copy.
func SumIndex(xs []Big) (s int) {
	for i := range xs {
		s += xs[i].ID
	}
	return
}
go
// Package bce holds three loops to inspect with the bounds-check-elimination debug flag.
package bce

func Classic(s []int, n int) int {
	t := 0
	for i := 0; i < n; i++ {
		t += s[i]
	}
	return t
}

func Range(s []int) int {
	t := 0
	for i := range s {
		t += s[i]
	}
	return t
}

func Hint(s []int) int {
	_ = s[3]
	return s[0] + s[1] + s[2] + s[3]
}

Tools that watch your loops ​

ToolCommandCatches
compilergo build ./...unused labels, bad goto, fallthrough misuse
vetgo vet ./...loopclosure, unreachable code, self-assignment, shadowing with -vettool
race detectorgo test -race ./...goroutines sharing a captured variable or map
lintersgolangci-lint runold x := x copies and loops convertible to range over integer (linters named copyloopvar and intrange; not run here)
loopvar reportgo build -gcflags=all=-d=loopvar=2 and the bisect toolwhich loops compile differently under the new semantics (LoopvarExperiment wiki)

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
Deeply nested ifguard clausesreturn or continue earlyflat codeseveral exit points
Long else if chaintagless switchswitch { case ...: }aligned, readablesame cost as if
Leave nested loopslabelbreak outerno flag variablesa name to maintain
Stable map outputsorted keysslices.Sorted(maps.Keys(m))deterministicO(n log n)
Closure over loop variablego.mod 1.22 or copyraise go line; or v := vcorrect valuesversion coupling
Many defer in a loophelper functionone function per itembounded resourcesextra call
Custom traversaliter.Seqreturn func(yield ...)lazy, no goroutinemust respect yield
Ticker leakNewTicker + Stopdefer t.Stop()explicit lifetimea few lines
Illegal state changesstate machine in switchone transition functiontestable, replayablegrows with states
Spinning loopblock or sleepchannel, timer, contextno 100% CPUdesign needed

Guard clauses and the init statement ​

Shown in the branching snippet above: ParseQty runs in four lines of happy path; the nested twin is the same logic indented three levels. Both pass the same tests, so refactoring from one to the other is safe.

A state machine as a switch ​

In plain words: a state machine is a table of "from this state, on this event, go to that state". In Go the table is a nested switch, which the compiler checks for duplicate constants.

Common misunderstanding: "Use a map of functions, a switch is not scalable." For a few dozen states a switch is faster to read, trivially testable and has no initialisation order problems. Move to a table when states are data (loaded from configuration).

Definition: Next(state, event) (state, error) is a pure function; Replay(events) folds a log of events with a for loop and stops on the first illegal one. Terminal states reject every event.

1  New --pay--> Paid
2  Paid --ship--> Shipped
3  New or Paid --cancel--> Cancelled
4  Shipped or Cancelled --any--> error "... is terminal"

Real scenarios: orders and payments, saga steps, WebSocket connection phases, parsers (lexer states), job lifecycles (queued, running, done, failed). Persisting the state is a database concern:

sql
-- the machine's current state is one column; the guarded update makes the transition atomic
UPDATE orders
SET state = 'paid', updated_at = now()
WHERE id = $1 AND state = 'new';
-- 0 rows updated means the order was not 'new': reject the event
go
// Package machine is a small order state machine written as a switch.
package machine

import "fmt"

type State int

const (
	New State = iota
	Paid
	Shipped
	Cancelled
)

func (s State) String() string {
	switch s {
	case New:
		return "new"
	case Paid:
		return "paid"
	case Shipped:
		return "shipped"
	case Cancelled:
		return "cancelled"
	}
	return fmt.Sprintf("State(%d)", int(s))
}

// Next applies an event to a state. Illegal transitions are errors, so a
// replayed or out-of-order event cannot corrupt the order.
func Next(s State, event string) (State, error) {
	switch s {
	case New:
		switch event {
		case "pay":
			return Paid, nil
		case "cancel":
			return Cancelled, nil
		}
	case Paid:
		switch event {
		case "ship":
			return Shipped, nil
		case "cancel":
			return Cancelled, nil
		}
	case Shipped, Cancelled:
		return s, fmt.Errorf("%v is terminal: event %q", s, event)
	}
	return s, fmt.Errorf("illegal transition %v --%s-->", s, event)
}

// Replay folds a list of events with a for loop and stops at the first error.
func Replay(events []string) (State, error) {
	s := New
	for _, e := range events {
		var err error
		if s, err = Next(s, e); err != nil {
			return s, err
		}
	}
	return s, nil
}

Testing the statements ​

Every file above has a _test.go that pins the behaviour: closures see 0,1,2 on go 1.24; the shared-variable emulation sees 3,3,3; Perms(3) is [delete write read]; Run takes the goto path. Run go test -race ./... from the module root.

Choosing ​

SituationUseReason
Validate input before the workguard clausesflat happy path
One variable only needed in the conditionif with initsmaller scope
Two or three branches on one valueswitchno repeated variable name
Ranges and conditionstagless switchreads like a table
Many string commandsswitchcompiler rejects duplicates
State and eventsnested switch or tableone transition function
Branch on interface dynamic typetype switchno repeated assertions
Repeat n timesfor range n (Go 1.22)shortest and clear
Iterate a slicefor i, v := rangeno off-by-one
Modify slice elementsfor i := range and xs[i]v is a copy
Stable order over a mapsort keys, or slices.Sorted(maps.Keys(m))order is random
Leave nested loopslabeled breakclearer than flags
Cleanup shared by many exitsdefer, rarely gotodefer also runs on panic
Custom lazy traversal in-processiter.Seqno goroutine
Producer and consumer concurrentchannel and goroutinereal concurrency
Periodic workNewTicker + Stop + selectexplicit lifetime

In architecture: from a single process to a distributed system ​

Control flow is not an architecture topic until a loop crosses a process boundary: a for that retries a call, a range over a message stream, a switch over event types. The statements do not change; what changes is what can go wrong inside them.

Monolith: one process, one database ​

All loops run in one process and one address space. The traps are the local ones on this page: closures over loop variables, maps in random order, defers in a loop. A web handler uses guard clauses (validate, authorise, act) and a switch on the HTTP method; a nightly job ranges over rows from database/sql with for rows.Next() and checks rows.Err() after the loop. The Laravel parallel is a controller with early abort() calls and a Collection each.

Modular monolith and multiple databases ​

Modules own their state machines. The orders module exports Next and Replay; other modules send events, never write the state column. A loop that ranges over several modules' results must pick a deterministic order (sorted module names), otherwise logs and tests become flaky. Labels are useful when a batch spans modules and one failure should skip the whole batch: continue batch.

Microservices ​

A retry loop is the main control-flow pattern across services:

1  for attempt := range maxAttempts {          // Go 1.22 range over integer
2      err := callInventory(ctx)
3      switch {
4      case err == nil:               return nil
5      case !retryable(err):          return err   // guard: do not retry 4xx
6      case ctx.Err() != nil:         return ctx.Err()
7      }
8      sleep(backoff(attempt))        // timer with select on ctx.Done()
9  }

Consumers use for msg := range deliveries with a switch on msg.Type, and an unknown type goes to a dead-letter path (see Dead-Letter Queues). range over a channel stops when the channel is closed; if nobody closes it the consumer goroutine leaks. Idempotency matters because a loop that crashes midway is re-run: see Idempotent Consumers & the Inbox Pattern.

Distributed data: replicas, caches, NAT and containers ​

Paged reads from replicas are loops over pages: for { page, next := fetch(cursor); ...; if next == "" { break } }. The cursor shape is the design; see Pagination: Offset vs Keyset. Wrap such loops in iter.Seq2[Item, error] so callers can break and the connection is released through the iterator's defer. Replica lag means a loop that reads "until empty" can see an item twice or miss it; write loops that tolerate both. A for range time.Tick leader-lease renewer that never stops can keep a node believing it still holds a lease: tie it to a context.

Scaling path: 1×, 10×, 100× ​

ScaleControl-flow concernAction
1x (one process)correctness: copies, map order, loop variablestests, go vet, go.mod at 1.22+
10x (many requests)per-request loops allocate; defer in loops holds descriptorshelper functions, pre-sized slices, measure with pprof
100x (many services)retry storms: loops without backoff multiply loadcapped attempts, jitter, circuit breaking, context deadlines
anyunbounded for over a streambounded batches, backpressure, cancellation

Lab ​

Everything here runs on a laptop with Go 1.24 or later; no Docker. Outputs marked "(real)" were produced on the host while writing this page (Go 1.27.4, macOS arm64); anything else is labelled "expected, not run".

bash
cd docs/snippets/go/control-flow/go
gofmt -l .            # no output
go vet ./...          # no output
go test -race ./...   # ok for 9 packages (real)

1. Random map order (real) ​

bash
go run ./maporder
# run 1: b c d e a
# run 2: a b c d e
# run 3: b c d e a

Run it several times: the three lines differ between runs and between lines.

2. The loop-variable fix ​

bash
go test -v ./loopvar
# --- PASS: TestCapture (0.00s)      # 0,1,2 with go 1.24 in go.mod
# --- PASS: TestPointers (0.00s)

To see the gate, make a throwaway module whose go.mod says go 1.21 and run the classic closure loop. Real output on the Go 1.27 toolchain:

3 3 3

With go 1.24 the same program prints 0 1 2. In the go 1.21 module a for i := range 3 does not even compile: cannot range over 3 (untyped int constant): requires go1.22 or later (-lang was set to go1.21; check go.mod).

3. Iterator that ignores yield (real) ​

Write a func(yield func(int) bool) that calls yield(i) without checking the result and break out of the for range. Real output:

0
panic: runtime error: range function continued iteration after function for loop body returned false

4. Bounds-check report (real) ​

bash
go build -gcflags=-d=ssa/check_bce/debug=1 ./bce
# bce/bce.go:7:9: Found IsInBounds
# bce/bce.go:21:7: Found IsInBounds

5. Benchmark (real, single run) ​

bash
go test -bench . -run xxx ./rangecost
# BenchmarkValue-12   4792224   246.0 ns/op
# BenchmarkIndex-12   3838761   310.2 ns/op

6. Index out of range (real) ​

go
s := []int{1, 2, 3}
i := 3
fmt.Println(s[i])
// panic: runtime error: index out of range [3] with length 3

7. Compiler messages (real) ​

A file with an unused label, range 3.5, a goto over x := 1, fallthrough in the last case, a duplicate case and if 1 {} produced, in order:

label outer defined and not used
cannot range over 3.5 (untyped float constant)
goto L jumps over declaration of x at ./main.go:14:4
cannot fallthrough final case in switch
duplicate case 1 (constant of type int) in expression switch
non-boolean condition in if statement

Common misconceptions ​

BeliefReality
switch needs breakCases do not fall through; break is rarely needed
break in a switch stops the loop around itIt ends only the switch; use a label
The loop variable is sharedPer-iteration since Go 1.22 when go.mod says 1.22 or later
range gives the element itselfIt gives a copy; write through the index
Map iteration is in insertion orderIt is unspecified and randomised
defer runs at the end of each loop iterationIt runs when the function returns
for can only loop over indexesIt ranges over integers, strings, maps, channels and functions
fallthrough tests the next caseIt jumps into the next body without testing
goto is forbiddenLegal, with scope rules; used sparingly
time.Tick always leaksCollectable since Go 1.23 only when go.mod says 1.23 or later
if x works for non-bool valuesThe condition must be a bool
An iterator can ignore yieldIgnoring a false result panics at run time
Deleting from a map while ranging is a crashIt is allowed; concurrent writes from other goroutines crash

Cheat sheet ​

TopicWhat to remember
ifbool only, braces always, init statement scopes variables
guard clausereturn early; keep the happy path unindented
switchno fall-through, many values per case, default anywhere
tagless switchcases are booleans, first true wins
fallthroughlast statement of a non-final clause; not in type switch
type switchswitch v := x.(type); single-type case gives v that type
forthree forms plus range; no while
rangestring gives byte offset and rune; map order random; value is a copy
range nGo 1.22, zero or negative runs zero times
range over funcGo 1.23, respect yield returning false
loop variableper-iteration when go.mod is 1.22 or later
labelsbreak L, continue L; unused label is an error
gotosame function, cannot skip declarations
defer in a loopruns at function return; wrap the body in a function
selectswitch for channels; break leaves the select
mapssort keys for stable output; delete during range is fine
tickersNewTicker + defer Stop(); time.Tick only in modules at 1.23+
boundsrange removes checks; _ = s[3] hint

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What does for i := range 3 { } print if the body prints i, and which Go version added it? Important ​

Answer

Answer: It prints 0, 1, 2. Go 1.22 added range over integers.

2 — A loop starts goroutines with go func() { fmt.Println(i) }(). What do they print on a module with go 1.21, and with go 1.24? Must-know ​

Answer

Answer: With go 1.21 semantics all goroutines tend to print the final value (one shared variable). With go 1.24 each prints its own iteration's value.

3 — Why does break inside a switch inside a for not end the loop, and how do you fix it? Must-know ​

Answer

Answer: break terminates the innermost for, switch or select; here that is the switch. Label the for and write break label.

4 — What are the two values of for i, r := range "aé"? Must-know ​

Answer

Answer: i is the byte offset (0 then 1) and r is the rune ('a' then 'é'); the next offset after 'é' would be 3 because it takes two bytes.

5 — Why does for _, it := range items { it.N++ } not change the slice? Must-know ​

Answer

Answer: it is a copy of each element. Use items[i].N++ or a slice of pointers.

6 — A map is ranged and an entry not yet reached is deleted. What happens? Important ​

Answer

Answer: It will not be produced. Entries added during iteration may or may not be produced. Order is unspecified.

7 — Why is defer f.Close() inside a loop over 10,000 files a bug? Must-know ​

Answer

Answer: Defers run when the function returns, so all 10,000 files stay open. Move the body to a helper function.

8 — What does an iter.Seq have to do when yield returns false? Good to know ​

Answer

Answer: Return immediately. Calling yield again panics with "range function continued iteration after function for loop body returned false".

9 — When can fallthrough not be used? Good to know ​

Answer

Answer: In a type switch, and in the final clause of any switch.

10 — Is time.Tick safe in a module whose go.mod says go 1.22? Important ​

Answer

Answer: No: the Go 1.23 collection behaviour is enabled only for modules with go 1.23 or later; use NewTicker and Stop.

11 — What does go build -gcflags=-d=ssa/check_bce/debug=1 show? Good to know ​

Answer

Answer: Each remaining run-time bounds check (Found IsInBounds) with file and line.

Glossary ​

TermMeaning
ifconditional statement with a bool condition
init statementsimple statement before the condition (if v, ok := m[k]; ok)
early returnleaving a function as soon as a precondition fails
guard clausean early-return if placed before the main logic
happy paththe normal, error-free sequence of statements
switchmulti-way branch; first matching case runs
tagless switchswitch with no tag; cases are boolean expressions
fallthroughcontinue into the next case body unconditionally
type switchswitch v := x.(type) branching on dynamic type
forGo's only loop keyword
rangeiteration clause over slices, arrays, strings, maps, channels, integers, functions
range over integerfor i := range n, Go 1.22
range over funciteration with a function as the source, Go 1.23
iter.Seqfunc(yield func(V) bool)
iter.Seq2func(yield func(K, V) bool)
iteratorfunction that produces values by calling yield
yieldthe loop body, as a function the iterator calls
iter.Pullconverts a push iterator to next and stop functions
loop variablevariable declared by the for clause
per-iteration variablea fresh copy of the loop variable each iteration (Go 1.22)
closure capturea function literal referring to an outer variable
labelname placed before a statement as a jump target
breakleave the innermost for, switch or select
continuestart the next iteration of the innermost for
gotojump to a label in the same function
defer in loopdeferred call that runs at function return, not loop end
selectswitch for channel operations
map iteration orderunspecified and randomised
range copythe element value received by range is a copy
state machinestates plus legal transitions, here a nested switch
bounds checkrun-time test that an index is below the length
time.Tick leakticker without a way to stop it, collectable only on go 1.23+ modules

References ​

All URLs returned HTTP 200 when fetched on 26 November 2026; pages saved under the scratchpad sources/control-flow/ folder.

Built by Morteza Negahi