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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why Go has so few statements | Why it exists |
| Where the rules come from, which Go version added what | Where it comes from |
if err != nil, scoped variables, else after return | if and the init statement and Early return and guard clauses |
switch without break, several values per case | Expression switch |
switch { case x > 1: } | Tagless switch |
fallthrough and where it is forbidden | fallthrough |
switch v := x.(type) | Type switch |
for in its three shapes | The for statement |
range over slices, strings, maps, channels | range sources |
for i := range 10 | Range over an integer |
iter.Seq, iter.Seq2, iter.Pull | Range over a function |
| Closures that all print the last value | Loop variables |
break outer, continue outer, goto | Labels, break, continue and goto |
defer inside a loop | defer in a loop |
What select is, in one page | select |
| Random map order, deleting while ranging | Maps and range |
index out of range, yield panic, vet output | Mechanics |
| Bounds checks, range over big structs | Performance |
State machines, time.Tick, fixes in code | Solving the classic problems |
| Which construct for which situation | Choosing |
| One process to many services | In architecture |
| Run it yourself | Lab |
Everything in one minute
| Statement | Plain words | Tiny example | Gotcha |
|---|---|---|---|
if | Run a block when a bool is true | if n < 0 { return } | No parentheses, braces mandatory, only bool conditions |
if init | Declare a variable that lives only in the if/else chain | if v, ok := m[k]; ok {} | v and ok are gone after the chain |
switch | First matching case runs, then the switch ends | switch day { case "sat", "sun": } | No fall-through unless you write fallthrough |
tagless switch | A tidy if/else if chain | switch { case n > 9: } | Cases are evaluated top to bottom, first true wins |
type switch | Branch on the dynamic type of an interface | switch v := x.(type) | fallthrough is not allowed here |
for | The only loop keyword | for i := 0; i < n; i++ {} | There is no while or do |
for cond | While-style loop | for n > 1 {} | Infinite if the condition never changes |
for {} | Infinite loop | for { ... break } | Needs a break, return or panic to end |
for range | Iterate a collection | for i, v := range xs {} | v is a copy of the element |
for range n | Repeat n times (Go 1.22) | for i := range 3 {} | n must be an integer; zero or negative runs zero times |
| range over func | Custom iterators (Go 1.23) | for v := range seq {} | The iterator must stop when yield returns false |
break | Leave the innermost for, switch or select | break | Inside a switch it does NOT leave the surrounding loop |
continue | Next iteration of the innermost for | continue | Not valid in switch outside a loop |
| label | A name for the statement it precedes | outer: for {} | An unused label is a compile error |
goto | Jump to a label in the same function | goto cleanup | Cannot jump over a variable declaration or into a block |
| Go version | What changed for control flow | Where |
|---|---|---|
| 1.0 | if, switch, for, range, labels, goto, select | spec |
| 1.22 | Per-iteration loop variables; range over integers | Loop variables, Range over an integer |
| 1.23 | Range over functions; iter package; time.Tick garbage-collectable | Range over a function, Ticker leaks |
| 1.24 | testing.B.Loop replaces for i := 0; i < b.N; i++ in benchmarks | Performance |
| 1.25 | Release notes: nothing in the statements themselves; semantics unchanged | Mechanics |
| Mistake | Symptom | Section |
|---|---|---|
| Closure captures loop variable on go.mod below 1.22 | Every goroutine sees the last value | Loop variables |
| Modify the range copy | Slice does not change | range copies values |
| Rely on map order | Flaky tests, unstable JSON | Maps and range |
break inside switch inside for | Loop keeps running | Labels |
defer in a long loop | Memory and file descriptors pile up until return | defer in a loop |
for with no yield | 100% CPU, other work starves | Infinite loops |
time.Tick in old modules | Ticker never freed | Ticker 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 choice | What you give up | What you get |
|---|---|---|
One loop keyword for | while, do-while, foreach spelling | One thing to learn; every loop has the same layout |
| Braces always, no parentheses | Brace-less one-liners | No "goto fail" style bug, shorter conditions |
switch breaks by default | Concise fall-through tricks | The common case is the safe case |
if/switch init statement | Declaring variables above the statement | Smaller scope, fewer leaked names |
| Per-iteration loop variables | C-style "one shared counter" mental model | Closures and goroutines behave as written |
| No exceptions, errors are values | Short try/catch blocks | Error 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
- "
switchneedsbreaklike in C or PHP." It does not; the first matching case runs and the switch ends. The mistake goes the other way: abreakinside aswitchinside aforleaves only the switch. - "The loop variable is one variable that changes." That was true until Go 1.22. With
go 1.22or later ingo.modevery iteration has its own copy, which silently fixes a famous bug and silently changes the meaning of old code if you raise the version. - "
rangegives 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:
| Change | Release | Primary source |
|---|---|---|
| "For" loops may range over integers | Go 1.22 | go.dev/doc/go1.22 |
Loop variables created anew for each iteration (gated on the go line in go.mod) | Go 1.22 | go.dev/doc/go1.22, go.dev/blog/loopvar-preview |
iter package and range-over-func | Go 1.23 | go.dev/doc/go1.23, go.dev/blog/range-functions |
Unreferenced Timers and Tickers are collectable; timer channels unbuffered | Go 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: vReal 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.
| Language | if condition type | Parentheses | Brace-less body | Init statement |
|---|---|---|---|---|
| Go | bool only | not used | not allowed | yes |
| PHP | any value (truthiness) | required | allowed | no |
| C | any scalar | required | allowed | no (C99 has it in for only) |
| Rust | bool only | not used | not allowed | no (if let instead) |
| Java | boolean only | required | allowed | no |
Fix / how to use it: keep init statements short; if the line gets long, declare the variable on its own line above.
if v, ok := m[k]; ok {
return "found " + strconv.Itoa(v)
}
return "missing"The full runnable file with tests:
// 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.
| Style | Indent depth for 3 checks | Where the happy path lives | Reviewer reaction |
|---|---|---|---|
| Guard clauses | 1 | Bottom, unindented | Preferred |
else chains after return | 3 | Innermost block | Flagged |
Single exit with result variable | 1-2 | Anywhere | Accepted 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: skippedReal 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.
| Feature | Go switch | PHP switch | PHP match | C switch |
|---|---|---|---|---|
| Fall-through by default | No | Yes | No | Yes |
| Comparison | == on the tag, any comparable type | loose == | strict === | integer constants only |
| Non-constant cases | Yes | Yes | Yes | No |
| Returns a value | No (statement) | No | Yes (expression) | No |
| Missing case | silently nothing | silently nothing | UnhandledMatchError | silently 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 evaluatedReal 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.
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| Form | Spelling | Typical use |
|---|---|---|
| Classic | for i := 0; i < n; i++ | Index math, counting down, two indexes |
| Condition | for n > 1 | Until a value converges, drain a buffer |
| Infinite | for { } | Servers, select loops, retry with break |
| Range | for i, v := range x | Collections, channels, iterators |
| Range, no variables | for range ch or for range 3 | Run 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// 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 over | First value | Second value | Notes |
|---|---|---|---|
| array, slice, pointer to array | index | copy of element | length fixed at loop start for slices (the slice header is copied) |
| string | byte index of the rune | rune (int32) | invalid UTF-8 yields U+FFFD and advances one byte |
| map | key | value | order is unspecified and varies run to run |
| channel | element | none | runs until the channel is closed; nil channel blocks forever |
| integer n | 0 .. n-1 | none | Go 1.22; n of zero or less runs zero times |
func(yield func() bool) | none | none | Go 1.23 |
func(yield func(V) bool) | V | none | iter.Seq[V] |
func(yield func(K, V) bool) | K | V | iter.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) = 3Real scenarios: counting characters, validating names, draining a worker channel, walking config maps in sorted order for stable output.
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 iterationsReal scenarios: retry attempts (for attempt := range maxAttempts), spawning N workers, benchmarks, table generation.
| Spelling | Meaning | Need Go |
|---|---|---|
for i := 0; i < n; i++ | classic | any |
for i := range n | same, shorter | 1.22 |
for range n | n times, no variable | 1.22 |
for i := n - 1; i >= 0; i-- | downward; no range equivalent | any |
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 possibleReal 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).
| Type | Shape | Producer examples |
|---|---|---|
iter.Seq[V] | one value per step | slices.Values, maps.Keys, your own generators |
iter.Seq2[K, V] | two values per step | slices.All, maps.All |
iter.Pull | pull style: next() and stop() | zipping two sequences, merging |
| channel | goroutine to goroutine | when 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.
// 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, 2Real 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.
| Pattern | go.mod below 1.22 | go.mod 1.22 or later |
|---|---|---|
closure over i in classic for | all see the final value | each sees its own |
&v stored from range | all pointers equal | distinct pointers |
v := v copy at top of body | needed | redundant, harmless |
go func(v T) { ... }(v) argument | works | works |
modifying i inside the body | affects the one variable | carried 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.
// 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 loopsReal 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.
| Statement | Target | Valid inside |
|---|---|---|
break | innermost for, switch, select | those three |
continue | innermost for | for (also nested in switch) |
break L | enclosing statement labeled L | for, switch, select |
continue L | enclosing for labeled L | for only |
goto L | any label in the same function | anywhere, 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.
// 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.
| Approach | Files open at once | Closes on panic | Cost |
|---|---|---|---|
defer in the loop body | all of them | yes, at function return | memory and descriptors |
helper function with defer | one | yes | one call per item |
explicit Close after use | one | no | forgotten 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 aReal 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 m | Allowed | Result |
|---|---|---|
delete(m, k) | yes | an unreached deleted key is not produced |
m[newKey] = v | yes | may or may not be visited |
m[existing] = v2 | yes | later visit sees the new value |
| concurrent write from another goroutine | no | fatal error: concurrent map iteration and map write |
clear(m) | yes (Go 1.21) | remaining entries not produced |
// 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 itReal scenarios: health-check pollers, metric flushers, leader-lease renewals, cache refreshers started with go poll() and never cancelled.
// 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
| Text | Meaning | Fix |
|---|---|---|
panic: runtime error: index out of range [3] with length 3 | indexing a slice or array past its length at run time | check the length, range over the slice |
panic: runtime error: slice bounds out of range [:5] with capacity 3 | slicing beyond capacity | validate bounds |
panic: runtime error: range function continued iteration after function for loop body returned false | an iterator ignored yield returning false | return when yield is false |
fatal error: concurrent map iteration and map write | map written while another goroutine ranges | guard with a mutex or copy keys first |
fatal error: concurrent map writes | two goroutines wrote one map | mutex or sync.Map |
fatal error: all goroutines are asleep - deadlock! | every goroutine blocked, for example range ch over a channel nobody closes | close the channel, see Goroutines & Channels |
label outer defined and not used | compile error: label never targeted | remove it or use it |
goto L jumps over declaration of x at ./main.go:14:4 | compile error: jump skips a declaration | move the declaration before the goto |
cannot fallthrough final case in switch | fallthrough in the last clause | remove it |
non-boolean condition in if statement | non-bool condition | write the comparison |
cannot range over 3.5 (untyped float constant) | range needs a rangeable type | use an integer, slice, string, map, channel or function |
duplicate case 1 (constant of type int) in expression switch | the same constant twice | remove one |
unreachable code (vet) | statements after return, panic, infinite for | delete or restructure |
loopclosure (vet) | loop variable captured by go/defer closure in older modules | raise go line or copy |
Version gates, in one table Must-know
| Feature | Needs go line | What happens below |
|---|---|---|
for i := range 10 | 1.22 | compile 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 variables | 1.22 | one shared variable |
for v := range seq (functions) | 1.23 | compile error: cannot range over function (needs go1.23) |
iter, maps.Keys, slices.Sorted | 1.23 | package or symbol missing |
collectable Ticker/Timer, unbuffered timer channels | 1.23 | old buffered, never-collected behaviour |
testing.B.Loop | 1.24 | not defined |
clear on maps and slices | 1.21 | undefined: 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/opThe 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.
// 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
}// 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
| Tool | Command | Catches |
|---|---|---|
| compiler | go build ./... | unused labels, bad goto, fallthrough misuse |
| vet | go vet ./... | loopclosure, unreachable code, self-assignment, shadowing with -vettool |
| race detector | go test -race ./... | goroutines sharing a captured variable or map |
| linters | golangci-lint run | old x := x copies and loops convertible to range over integer (linters named copyloopvar and intrange; not run here) |
| loopvar report | go build -gcflags=all=-d=loopvar=2 and the bisect tool | which loops compile differently under the new semantics (LoopvarExperiment wiki) |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
Deeply nested if | guard clauses | return or continue early | flat code | several exit points |
Long else if chain | tagless switch | switch { case ...: } | aligned, readable | same cost as if |
| Leave nested loops | label | break outer | no flag variables | a name to maintain |
| Stable map output | sorted keys | slices.Sorted(maps.Keys(m)) | deterministic | O(n log n) |
| Closure over loop variable | go.mod 1.22 or copy | raise go line; or v := v | correct values | version coupling |
Many defer in a loop | helper function | one function per item | bounded resources | extra call |
| Custom traversal | iter.Seq | return func(yield ...) | lazy, no goroutine | must respect yield |
| Ticker leak | NewTicker + Stop | defer t.Stop() | explicit lifetime | a few lines |
| Illegal state changes | state machine in switch | one transition function | testable, replayable | grows with states |
| Spinning loop | block or sleep | channel, timer, context | no 100% CPU | design 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:
-- 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// 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
| Situation | Use | Reason |
|---|---|---|
| Validate input before the work | guard clauses | flat happy path |
| One variable only needed in the condition | if with init | smaller scope |
| Two or three branches on one value | switch | no repeated variable name |
| Ranges and conditions | tagless switch | reads like a table |
| Many string commands | switch | compiler rejects duplicates |
| State and events | nested switch or table | one transition function |
| Branch on interface dynamic type | type switch | no repeated assertions |
| Repeat n times | for range n (Go 1.22) | shortest and clear |
| Iterate a slice | for i, v := range | no off-by-one |
| Modify slice elements | for i := range and xs[i] | v is a copy |
| Stable order over a map | sort keys, or slices.Sorted(maps.Keys(m)) | order is random |
| Leave nested loops | labeled break | clearer than flags |
| Cleanup shared by many exits | defer, rarely goto | defer also runs on panic |
| Custom lazy traversal in-process | iter.Seq | no goroutine |
| Producer and consumer concurrent | channel and goroutine | real concurrency |
| Periodic work | NewTicker + Stop + select | explicit 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×
| Scale | Control-flow concern | Action |
|---|---|---|
| 1x (one process) | correctness: copies, map order, loop variables | tests, go vet, go.mod at 1.22+ |
| 10x (many requests) | per-request loops allocate; defer in loops holds descriptors | helper functions, pre-sized slices, measure with pprof |
| 100x (many services) | retry storms: loops without backoff multiply load | capped attempts, jitter, circuit breaking, context deadlines |
| any | unbounded for over a stream | bounded 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".
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)
go run ./maporder
# run 1: b c d e a
# run 2: a b c d e
# run 3: b c d e aRun it several times: the three lines differ between runs and between lines.
2. The loop-variable fix
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 3With 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 false4. Bounds-check report (real)
go build -gcflags=-d=ssa/check_bce/debug=1 ./bce
# bce/bce.go:7:9: Found IsInBounds
# bce/bce.go:21:7: Found IsInBounds5. Benchmark (real, single run)
go test -bench . -run xxx ./rangecost
# BenchmarkValue-12 4792224 246.0 ns/op
# BenchmarkIndex-12 3838761 310.2 ns/op6. Index out of range (real)
s := []int{1, 2, 3}
i := 3
fmt.Println(s[i])
// panic: runtime error: index out of range [3] with length 37. 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 statementCommon misconceptions
| Belief | Reality |
|---|---|
switch needs break | Cases do not fall through; break is rarely needed |
break in a switch stops the loop around it | It ends only the switch; use a label |
| The loop variable is shared | Per-iteration since Go 1.22 when go.mod says 1.22 or later |
range gives the element itself | It gives a copy; write through the index |
| Map iteration is in insertion order | It is unspecified and randomised |
defer runs at the end of each loop iteration | It runs when the function returns |
for can only loop over indexes | It ranges over integers, strings, maps, channels and functions |
fallthrough tests the next case | It jumps into the next body without testing |
goto is forbidden | Legal, with scope rules; used sparingly |
time.Tick always leaks | Collectable since Go 1.23 only when go.mod says 1.23 or later |
if x works for non-bool values | The condition must be a bool |
An iterator can ignore yield | Ignoring a false result panics at run time |
| Deleting from a map while ranging is a crash | It is allowed; concurrent writes from other goroutines crash |
Cheat sheet
| Topic | What to remember |
|---|---|
if | bool only, braces always, init statement scopes variables |
| guard clause | return early; keep the happy path unindented |
switch | no fall-through, many values per case, default anywhere |
tagless switch | cases are booleans, first true wins |
fallthrough | last statement of a non-final clause; not in type switch |
type switch | switch v := x.(type); single-type case gives v that type |
for | three forms plus range; no while |
range | string gives byte offset and rune; map order random; value is a copy |
range n | Go 1.22, zero or negative runs zero times |
| range over func | Go 1.23, respect yield returning false |
| loop variable | per-iteration when go.mod is 1.22 or later |
| labels | break L, continue L; unused label is an error |
goto | same function, cannot skip declarations |
defer in a loop | runs at function return; wrap the body in a function |
select | switch for channels; break leaves the select |
| maps | sort keys for stable output; delete during range is fine |
| tickers | NewTicker + defer Stop(); time.Tick only in modules at 1.23+ |
| bounds | range removes checks; _ = s[3] hint |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| if | conditional statement with a bool condition |
| init statement | simple statement before the condition (if v, ok := m[k]; ok) |
| early return | leaving a function as soon as a precondition fails |
| guard clause | an early-return if placed before the main logic |
| happy path | the normal, error-free sequence of statements |
| switch | multi-way branch; first matching case runs |
| tagless switch | switch with no tag; cases are boolean expressions |
| fallthrough | continue into the next case body unconditionally |
| type switch | switch v := x.(type) branching on dynamic type |
| for | Go's only loop keyword |
| range | iteration clause over slices, arrays, strings, maps, channels, integers, functions |
| range over integer | for i := range n, Go 1.22 |
| range over func | iteration with a function as the source, Go 1.23 |
| iter.Seq | func(yield func(V) bool) |
| iter.Seq2 | func(yield func(K, V) bool) |
| iterator | function that produces values by calling yield |
| yield | the loop body, as a function the iterator calls |
| iter.Pull | converts a push iterator to next and stop functions |
| loop variable | variable declared by the for clause |
| per-iteration variable | a fresh copy of the loop variable each iteration (Go 1.22) |
| closure capture | a function literal referring to an outer variable |
| label | name placed before a statement as a jump target |
| break | leave the innermost for, switch or select |
| continue | start the next iteration of the innermost for |
| goto | jump to a label in the same function |
| defer in loop | deferred call that runs at function return, not loop end |
| select | switch for channel operations |
| map iteration order | unspecified and randomised |
| range copy | the element value received by range is a copy |
| state machine | states plus legal transitions, here a nested switch |
| bounds check | run-time test that an index is below the length |
| time.Tick leak | ticker 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.
- The Go Programming Language Specification (revision go1.27, 26 May 2026): go.dev/ref/spec (For statements, Switch statements, Break/Continue/Goto/Fallthrough, Labeled statements)
- Effective Go, "Control structures": go.dev/doc/effective_go
- Go FAQ: go.dev/doc/faq
- Go Code Review Comments, "Indent Error Flow": go.dev/wiki/CodeReviewComments
- Go 1.22 release notes (range over integers, loop variables): go.dev/doc/go1.22
- Go 1.23 release notes (iterators, timer changes): go.dev/doc/go1.23
- Go 1.25 release notes: go.dev/doc/go1.25
- Go 1.21 release notes: go.dev/doc/go1.21
- Go 1.24 release notes (testing.B.Loop): go.dev/doc/go1.24
- Go blog, "Fixing For Loops in Go 1.22": go.dev/blog/loopvar-preview
- Go blog, "Range Over Function Types": go.dev/blog/range-functions
- Go wiki, LoopvarExperiment: go.dev/wiki/LoopvarExperiment
- The Go Memory Model: go.dev/ref/mem