Go has no while: one for and all its forms
The four forms of for, why range gives a copy, switch and fallthrough, the break trap, labels, and the loop bug Go 1.22 fixed.
🌐 Oʻzbekcha · Русский · English
Lesson GO-1.05 · Go: 0 → Guru · ▶️ video coming soon · 💻 GitHub
This is the full written version of the video lesson: you can learn from it without watching (or hearing) the video. The video itself is in Uzbek.
What you will learn
One program, the same letter for letter. In one folder it prints a.uz b.uz c.uz, in another one it prints
c.uz c.uz c.uz. The difference is not in the program text. It is in one line of a settings file next to it. In
2020, a bug just like this made Let’s Encrypt issue more than 3 million certificates (security documents for websites) without a
required re-check. How
can this happen? At the end of the lesson we take it apart completely.
The one idea: in Go, every kind of repetition is written with one for. On each step the loop writes a copy of
the value into its own variable, and since Go 1.22 each step has its own, new variable.
By the end of the lesson you will be able to:
- read and write the four forms of
for(three-part, condition only, infinite,range); - know that
rangegives you a copy, not the element itself, and change a list through its index; - read
switchandfallthrough, and leave the whole loop from inside aswitchwith a label; - explain how one line in
go.modchanges how a loop behaves.
Three core new words today:
| Word | Plain meaning | Term |
|---|---|---|
| loop variable | a name label that the for itself creates: each step writes a new value into it | loop variable |
switch (choice) | picks one path out of many, based on one value | switch statement |
| label | a name given to a loop: it says which loop break leaves | label |
Two helper words also come up on the way: slice (a list of values of the same type) and address (where a variable sits in memory). We explain both where they are needed.
Before you start
- GO-0.05 · for: the computer never gets tired of repeating: loops, the counter
i,i++, infinite loops andbreak. - GO-0.04 · if: the program makes a decision:
<,==,true/falseandif. - GO-1.02 · Types and overflow: the types
intandstring, the zero value (the starting value of a variable that was declared but not given a value). - GO-1.04 · len(“oʻzbek”) = 7?: the difference between a byte and a rune.
- You can copy the programs into go.dev/play and run them with the Run button. Only the
experiment in the
eski/folder works with its owngo.modfile: run that one from the course folder. - If you downloaded the course code, open a terminal in the lesson folder (
lessons/005-for-switch): the commands below run from there.go run ./shakllarruns the program in theshakllarfolder, andgo run .runs the one in the current folder.
First, let’s recall the previous lesson. What is len("oʻzbek"), and why?
Answer
7. len counts bytes, not letters. The letter oʻ is made of two characters: o (1 byte) and ʻ (2 bytes).
Today we also recall what happens when range walks over such a string.
One for, four forms
When a program has to do the same thing many times, we write a loop: like the hand of a clock, it goes round and
repeats the same steps. Many languages have several words for this: for, while, do … while.
Go has 25 keywords. A keyword is a word that Go keeps for itself (for, if, func…); you cannot use it as a
name. while is not one of them. In Go, every loop is written with one for.
Two rules:
- parentheses
( )around the condition are not needed (Go’s formatting program,gofmt, removes them); - curly braces
{ }are required, even if there is only one line inside.
All four forms are in one program. This is shakllar/main.go (“forms”) from the course folder:
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ { // 1. uch qismli
fmt.Print(i, " ")
}
n := 1
for n < 100 { // 2. faqat shart (while)
n *= 2
}
fmt.Println("|", n)
for { // 3. cheksiz
n -= 50
if n < 0 {
break
}
}
fmt.Println(n)
for i := range 3 { // 4. son ustida (Go 1.22+)
fmt.Print(i, " ")
}
fmt.Println()
}| Line | Code | What it does |
|---|---|---|
| 1–5 | package main … func main() { | the familiar template: the program starts in main |
| 6 | for i := 0; i < 3; i++ { | form 1, three-part: start i := 0; condition i < 3; step i++ (adds 1 to i). Everything after // is a comment; Go does not read it |
| 7 | fmt.Print(i, " ") | prints i and one space. Print does not move to a new line (that is the difference from Println) |
| 9 | n := 1 | a new name label n with the value 1 |
| 10 | for n < 100 { | form 2, condition only: repeats while the condition is true. This is the while of other languages |
| 11 | n *= 2 | short for n = n * 2: let n become twice as big |
| 13 | fmt.Println("|", n) | prints the | sign and n, then moves to a new line |
| 14 | for { | form 3, infinite: no condition, the loop never stops by itself |
| 15 | n -= 50 | short for n = n - 50 |
| 16–18 | if n < 0 { break } | if n is negative, break leaves the loop |
| 20 | fmt.Println(n) | prints n after the loop |
| 21 | for i := range 3 { | form 4, range: gives i the values 0, 1, 2 in turn (3 itself is not included) |
| 24 | fmt.Println() | prints nothing, only moves to a new line |
The i on line 6 and the i on line 21 were created by the for itself (the := is right in the for line). It
is the same counter as in GO-0.05: on each round the name label stays in place and the value
under it changes. Such a name label, created by the loop itself, is called a loop variable: on each step
(iteration) a new value is written into it. The n on line 9 is not a loop variable: it was created earlier, on its
own.
range has been in Go from the start. Since Go 1.22 it can also walk over an integer: range 3 gives 0, 1, 2.
Before you run it, think: what will the second line of output be? A) 100 · B) 128 · C) -22
Answer
C: -22 (the first line ends with | 128). Form 2 doubles n until it goes over 100: 1, 2, 4,
8, 16, 32, 64, 128. 128 < 100 is false, so the loop stops. Then the infinite loop subtracts 50 each time: 78, 28,
−22. −22 is negative, so break runs. If you chose “100”: n is never exactly 100; it doubles and jumps over
100. And “128” is at the end of the first line.
$ go run ./shakllar
0 1 2 | 128
-22
0 1 2 The first line was built by two loops: Print does not move to a new line, so | 128 came right after 0 1 2 .
How n changed in memory:
| Where | Values of n | On screen |
|---|---|---|
| line 9 | 1 | |
| form 2 (10–12) | 2 → 4 → 8 → 16 → 32 → 64 → 128 (condition false) | | 128 |
| form 3 (14–19) | 78 → 28 → −22 (break) | -22 |
What range walks over
To walk with range, we first need to keep several values under one name. For example, three prices. Picture a
shelf with numbered boxes: each box holds one price, and the boxes are numbered from 0.
narxlar: [ 100 ][ 200 ][ 300 ]
index: 0 1 2In Go such a list is called a slice: []int{100, 200, 300} means “a list of ints with 100, 200, 300 in it”.
Each value in the list is an element, and its position number is its index. narxlar[0] is the element at
position 0, which is 100. We study slices in detail in GO-1.08.
range walks over more than numbers. On each step it gives one or two values:
| Over what | 1st value | 2nd value | Details in |
|---|---|---|---|
| slice | index | element (a copy!) | this lesson, GO-1.08 |
string (string) | position of the byte where the rune starts | rune | GO-1.04 |
| map (a “key → value” dictionary) | key | value; order is not guaranteed | GO-1.09 |
integer n (Go 1.22+) | 0, 1, …, n−1 | — | this lesson |
| channel (a pipe between goroutines) | values | — | GO-1.21 |
| function (Go 1.23+) | iterator | GO-1.18 |
For a value you don’t need, write _ (underscore): for _, n := range narxlar means “no index, only the
element”. If you only need the first value, leave the second one out: for i := range narxlar.
The trap: range gives a copy
We have a list of prices, narxlar (“prices”), and we want to double each price. Here is the first part of
nusxa/main.go (“copy”; we show the rest after the answer):
narxlar := []int{100, 200, 300}
for _, n := range narxlar {
n *= 2
}
fmt.Println(narxlar)- Line 6: the slice
narxlarwith 100, 200, 300. - Line 7: on each step
rangewrites the next element inton; the index is thrown away with_. - Line 8: let
nbecome twice as big. - Line 10: prints the whole slice.
Printlnprints a slice in square brackets:[1 2 3].
What does Println print? A) [100 200 300] · B) [200 400 600] · C) a compile error
Answer
A: [100 200 300]; the slice did not change. On each step range writes a copy of the element into n
(just like rekord := ochko in GO-0.02). We doubled the copy; nobody touched the original value
in the slice. If you chose “B”, you thought n was the element itself. Not “C”: the code is correct, it just does
not do what we wanted.
Each step in memory:
| Step | n (copy) | after n *= 2 | narxlar |
|---|---|---|---|
| 1 | 100 | 200 | [100 200 300] |
| 2 | 200 | 400 | [100 200 300] |
| 3 | 300 | 600 | [100 200 300] |
Now we run the whole file (it has a second output line too; we look at it below):
$ go run ./nusxa
[100 200 300]
[200 400 600]There are code checker programs that read code without running it and point out suspicious places. go vet comes
with Go. staticcheck is installed separately (go install honnef.co/go/tools/cmd/staticcheck@2026.2.1) and lands
in the $(go env GOPATH)/bin/ folder; the command below runs it from there.
$ go vet ./nusxa$ $(go env GOPATH)/bin/staticcheck ./nusxa
nusxa/main.go:8:3: this value of n is never used (SA4006)go vet is silent: it found nothing. staticcheck points to line 8, column 3: this value of n is never used.
In other words, the doubled copy goes nowhere.
So where did the correct result on the second line come from? Here is the whole file:
package main
import "fmt"
func main() {
narxlar := []int{100, 200, 300}
for _, n := range narxlar {
n *= 2
}
fmt.Println(narxlar)
for i := range narxlar {
narxlar[i] *= 2
}
fmt.Println(narxlar)
}- Line 12:
for i := range narxlartakes only the index: 0, 1, 2. - Line 13:
narxlar[i] *= 2doubles not a copy but the element itself, in boxiof the slice. - Line 15: now
[200 400 600].
Rule: to change an element of a slice, write to it through its index: narxlar[i].
switch: one path out of many
Think of a phone menu: “for your balance press 1, for your plan press 2”. One digit picks one path out of many. You
could write this as a chain of if … else if … else if, but Go has a separate choice statement for it: the
switch. Each path is called a case.
This is tanlov/main.go (“choice”). The function kun (“day”) takes the number of a weekday and returns its word:
package main
import "fmt"
func kun(d int) string {
s := ""
switch d {
case 6, 7: // bir nechta qiymat
s = "dam olish"
case 1:
s = "hafta boshi, "
fallthrough // keyingi case ham bajariladi
case 2, 3, 4, 5:
s += "ish kuni"
default:
s = "bunday kun yoʻq"
}
return s
}
func main() {
for _, d := range []int{1, 3, 7, 9} {
fmt.Println(d, kun(d))
}
}| Line | Code | What it does |
|---|---|---|
| 5 | func kun(d int) string { | our own function: takes d of type int, returns a string (functions: GO-1.06) |
| 6 | s := "" | a new name label s with an empty string |
| 7 | switch d { | one case is chosen based on the value of d |
| 8–9 | case 6, 7: | several values in one case: if 6 or 7, s = “dam olish” (“day off”) |
| 10–11 | case 1: | if 1, s = “hafta boshi, ” (“start of the week, “) |
| 12 | fallthrough | ”fall down”: run the body of the next case too |
| 13–14 | case 2, 3, 4, 5: | working days; s += "ish kuni" adds “ish kuni” (“working day”) to the end of s |
| 15–16 | default: | runs if no case matches (“bunday kun yoʻq” means “no such day”) |
| 18 | return s | gives s back to the place that called the function |
| 22 | for _, d := range []int{1, 3, 7, 9} { | walks over four numbers |
| 23 | fmt.Println(d, kun(d)) | prints the number and the word that kun returned |
An important difference: in C and in Java’s classic switch you must write break after each case, or the
program falls through into the next case. In Go each case ends by itself, so you don’t need break. If you
want to fall through, you say so explicitly: fallthrough.
Guess: what is printed for 1? A) 1 hafta boshi, · B) 1 hafta boshi, ish kuni · C) 1 ish kuni
Answer
B: 1 hafta boshi, ish kuni. case 1 wrote “hafta boshi, ”, then fallthrough dropped into the body of the
next case, which added “ish kuni”. Note: 1 is not in the list 2, 3, 4, 5, but fallthrough does not check
the next case’s condition; it just goes inside. If you chose “A”, you forgot about fallthrough; if you chose
“C”, you forgot that case 1 ran too.
$ go run ./tanlov
1 hafta boshi, ish kuni
3 ish kuni
7 dam olish
9 bunday kun yoʻqd | Which case | s |
|---|---|---|
| 1 | case 1 → fallthrough → case 2, 3, 4, 5 | ”hafta boshi, ” + “ish kuni” |
| 3 | case 2, 3, 4, 5 | ”ish kuni” |
| 7 | case 6, 7 | ”dam olish” |
| 9 | none → default | ”bunday kun yoʻq” |
In practice, fallthrough is rarely used.
break inside switch does not leave the loop
Now we put a switch inside a for. We want to find the first negative number and stop. This is break/main.go:
package main
import "fmt"
func main() {
sonlar := []int{4, 7, -1, 8, -5}
for _, s := range sonlar {
switch {
case s < 0:
fmt.Println("manfiy:", s, "→ toʻxtaymiz")
break // faqat switch'dan chiqadi
case s%2 == 0:
fmt.Println("juft:", s)
}
}
fmt.Println("tugadi")
}| Line | Code | What it does |
|---|---|---|
| 6 | sonlar := []int{4, 7, -1, 8, -5} | a slice sonlar (“numbers”) of five numbers |
| 7 | for _, s := range sonlar { | on each step the next number is written into s |
| 8 | switch { | a switch with no expression: nothing after switch. Then the first case that is true runs |
| 9–11 | case s < 0: | if s is negative, prints a message (“manfiy” means “negative”, “toʻxtaymiz” means “we stop”), and there is a break here |
| 12–13 | case s%2 == 0: | % is the remainder of a division: if s % 2 is 0, the number is even (“juft”) |
| 16 | fmt.Println("tugadi") | after the loop (“tugadi” means “finished”) |
7 is neither negative nor even: no case matches and there is no default, so nothing is printed for 7.
When a negative number is found, we wrote break. Does the loop stop? A) yes: juft: 4,
manfiy: -1 → toʻxtaymiz, tugadi · B) no: after −1, 8 and −5 are printed too · C) a compile error
Answer
B: the loop does not stop. Go’s official rule: “A “break” statement terminates execution of the innermost
“for”, “switch”, or “select” statement within the same function”. Here the box closest to break, the innermost
one, is the switch. break left only the switch, and the for went on to the next number. If you chose “A”,
you thought break always belongs to the loop.
$ go run ./break
juft: 4
manfiy: -1 → toʻxtaymiz
juft: 8
manfiy: -5 → toʻxtaymiz
tugadiA picture with boxes: break leaves only the innermost box it stands in.
┌ for ─────────────────────────────┐
│ ┌ switch ───────────────────┐ │
│ │ case s < 0: │ │
│ │ break ──► leaves │ │
│ │ the switch │ │
│ └───────────────────────────┘ │
│ for goes on: next s │
└──────────────────────────────────┘What do the code checkers say?
$ go vet ./break$ $(go env GOPATH)/bin/staticcheck ./break
break/main.go:11:4: ineffective break statement. Did you mean to break out of the outer loop? (SA4011)
break/main.go:11:4: redundant break statement (S1023)go vet is silent again. staticcheck finds exactly this bug, on line 11: ineffective break statement. Did you
mean to break out of the outer loop? The second line, redundant break statement, says this break is not needed
at all: in Go a case ends by itself, so this break does nothing.
The same trap exists with a select inside a for; we come back to select and this trap in the goroutine
lessons (GO-1.21).
This trap is not new. On 15 January 1990, the AT&T telephone network did not work properly for about nine hours.
According to a message that circulated in RISKS Digest (not an official AT&T statement), the cause was a break in
C code: it was written for an if, but it left the switch. There and here, the lesson is the same: break
belongs neither to if nor to case.
The fix: a label
To leave the loop, we give the for a name. In a house with several doors we don’t say “go out”, we say “go out
through the front door”. A name given to a loop is called a label. This is label/main.go; it differs from
break/main.go in only two lines:
package main
import "fmt"
func main() {
sonlar := []int{4, 7, -1, 8, -5}
qidiruv:
for _, s := range sonlar {
switch {
case s < 0:
fmt.Println("manfiy:", s, "→ toʻxtaymiz")
break qidiruv // for'dan chiqadi
case s%2 == 0:
fmt.Println("juft:", s)
}
}
fmt.Println("tugadi")
}- Line 7:
qidiruv:(“search”) is a name and a colon before thefor. Now this loop is calledqidiruv. - Line 12:
break qidiruvmeans “leave the loop calledqidiruv”. Nowbreakends exactly thisfor.
Guess: A) juft: 4, manfiy: -1 → toʻxtaymiz, tugadi · B) the same as the previous output ·
C) juft: 4, tugadi
Answer
A. First 4 is printed (it is even); nothing is printed for 7. Then −1 is found, the message is printed, and
break qidiruv leaves the whole loop: 8 and −5 never get their turn. If you chose “C”: the message is printed
before break.
$ go run ./label
juft: 4
manfiy: -1 → toʻxtaymiz
tugadiThree more things about labels:
continueworks with a label too. In nested loops,continue qidiruvdrops the inner loop and goes to the next step of the outer loop.- An unused label is a compile error (we see it below, in “Common mistakes”).
- Another way: move the loop into a separate function and
return.returnends the function at once.
Rule: if you are inside a switch and want to leave the loop, use a label.
One code, two results: Go 1.22 and the loop variable
Now we come back to the bug from the beginning. A domain is the name of a website, for example a.uz. We put a list
of domains into a queue to check them later. Into the queue we write not the domain itself but the address of
the loop variable d.
What is an address? Every variable sits somewhere in memory, the way a house stands on some street. You can write
down not the house but its address on a piece of paper. Later you go to the address and see who lives there now. In
Go, &d means “the address of d”, and *p means “the value at address p”. A value that holds an address is
called a pointer; we cover pointers in detail in GO-1.11.
This is manzil/main.go (“address”):
package main
import "fmt"
func main() {
domenlar := []string{"a.uz", "b.uz", "c.uz"}
var navbat []*string
for _, d := range domenlar {
navbat = append(navbat, &d) // d'ning manzili
}
for _, p := range navbat {
fmt.Print(*p, " ")
}
fmt.Println()
}| Line | Code | What it does |
|---|---|---|
| 6 | domenlar := []string{…} | a slice domenlar (“domains”) of three domain names |
| 7 | var navbat []*string | var declares a variable without giving it a value; navbat (“queue”) is “a list of string addresses” (*string = the address of a string), empty for now |
| 8 | for _, d := range domenlar { | d is the loop variable: on each step the next domain is written into it |
| 9 | navbat = append(navbat, &d) | append adds the address of d to the end of the list; the result is written back into navbat |
| 11 | for _, p := range navbat { | walks over the saved addresses |
| 12 | fmt.Print(*p, " ") | prints the value that is at address p now |
What does this program print? A) a.uz b.uz c.uz · B) address numbers starting with 0x… · C) an
error
Answer
A: a.uz b.uz c.uz (in our module). *p gives not the address itself but the value at that address, so it
prints domains, not numbers. fmt.Print(p) would print the address numbers.
$ go run ./manzil
a.uz b.uz c.uz Now the eski/ (“old”) folder. Its main.go is the same code, letter for letter, but the folder has its own
go.mod file. go.mod is the settings file of a folder. A folder with this file is called a module. The go
line in it says which version of the Go language rules the module is written for. The command grep '^go ' file
finds the line that starts with go in a file and prints it:
$ grep '^go ' ../../go.mod
go 1.26$ grep '^go ' eski/go.mod
go 1.21The course module says go 1.26, and eski/ says go 1.21. Now we go into eski/ (cd eski) and run the program:
$ cd eski && go run .
c.uz c.uz c.uz Why is it c.uz at all three addresses? A) old Go runs range backwards · B) all three addresses point to
one variable · C) append added the last element three times
Answer
B. If the go line is below 1.22, there is one d for the whole loop. Each step writes over that one d:
first a.uz, then b.uz, then c.uz. And &d is the same address every time. All three addresses point to one
variable, and the last value stayed in it. Not “A”: range always starts at element 0. Not “C”: append added
&d each time; it is just that &d was the same each time.
Memory picture (go 1.21, one d):
| Step | d (one box) | navbat |
|---|---|---|
| 1 | a.uz | [&d] |
| 2 | b.uz (a.uz is gone) | [&d &d] |
| 3 | c.uz (b.uz is gone) | [&d &d &d] |
c.uz | on screen: c.uz c.uz c.uz |
Since Go 1.22 (go 1.22 and higher), each step has its own d:
| Step | New d | navbat |
|---|---|---|
| 1 | d₁ = a.uz | [&d₁] |
| 2 | d₂ = b.uz | [&d₁ &d₂] |
| 3 | d₃ = c.uz | [&d₁ &d₂ &d₃] |
on screen: a.uz b.uz c.uz |
go 1.21: navbat[0] ─┐
navbat[1] ─┼──► d [ c.uz ] one box, each step wrote over it
navbat[2] ─┘
go 1.22+: navbat[0] ──► d₁ [ a.uz ]
navbat[1] ──► d₂ [ b.uz ] a new box on each step
navbat[2] ──► d₃ [ c.uz ]Do the code checkers find this bug?
$ cd eski && go vet . && $(go env GOPATH)/bin/staticcheck .No: both go vet and staticcheck are silent. (&& means “if the previous command succeeded, run the next one”.)
Let’s Encrypt, 2020, and the Go team’s decision
Let’s Encrypt gives websites free certificates for HTTPS (a safe, encrypted connection to a website). A certificate is the electronic document behind the lock icon in the browser: it confirms “this really is that website”. DNS is the “phone book” of the internet; it holds records about each domain. CAA is one such record: in it, the owner of a domain writes which organisations may issue certificates for it.
Before issuing a certificate, the Let’s Encrypt server (called Boulder) had to re-check the CAA record of every
domain. The code saved the address of the loop variable, just like our manzil program. As a result, in a request
with several domains, one domain was checked several times and the others were not re-checked. The most
interesting part: the code made a copy of k, with a comment, but forgot v. A simplified picture:
for k, v := range m {
// Make a copy of k because it will be reassigned with each loop.
kCopy := k ← k has a copy ✓
... &v ... ← v has no copy ✗
}| Date (UTC) | What happened |
|---|---|
| 24 April 2019 | the buggy code was added (still behind a setting that was off) |
| 23 August 2019 | the setting was turned on in production |
| 29 February 2020, 03:08 | the bug was confirmed |
| 29 February 2020, 05:22 | the fix went live: a little over two hours later |
The bug ran in production for more than half a year. It affected 3,048,289 certificates, and Let’s Encrypt revoked 1,711,396 of them. The first sentence of the incident report: “The proximate cause of the bug was a common mistake in Go: taking a reference to a loop iterator variable” (a reference here means an address).
Before changing the rule, the Go team tested it inside Google. Out of about 100,000 tests, 58 failed. In only 2 of them did the code really depend on the old behaviour; almost all the others were hidden bugs. And the second most common cause was exactly what we saw: appending the address of a loop variable to a slice.
After that, since Go 1.22:
- a variable declared by the loop itself is new on each iteration;
- a manual copy like
d := dis no longer needed; - but only in modules whose
goline ingo.modis 1.22 or higher. Code moved into a module with an old line brings the bug back (as ineski/).
We see how this line controls a program’s behaviour in GO-1.16.
Common mistakes
1. Thinking that break inside a switch stops the loop. This is the main trap of the lesson; we saw it above
in break/main.go: the program gives no error, but keeps going after −1. break leaves the innermost for,
switch or select. Fix: give the loop a label and write break qidiruv, or move the loop into a function and
return.
2. Changing the range value and thinking the slice changed. for _, n := range narxlar { n *= 2 } does not
touch the slice: n is a copy. staticcheck reports it as SA4006. Fix: narxlar[i] *= 2.
3. Writing while. People who come from another language often write this (this example is not in the course
folder; it was run separately):
package main
import "fmt"
func main() {
n := 1
while n < 100 {
n *= 2
}
fmt.Println(n)
}$ go run while/main.go
# command-line-arguments
while/main.go:7:8: syntax error: unexpected name n at end of statement
while/main.go:10:2: syntax error: non-declaration statement outside function bodywhile/main.go, line 7, column 8: syntax error: unexpected name n at end of statement. Go does not know while
as a keyword; it reads it as an ordinary name and does not understand what n is doing after it. The second line is
a result of the first error: Go got lost and decided the rest of the code is outside the function. Fix the first
error and the second one goes away too. Fix: use for instead of while: for n < 100 {.
4. Putting a three-part loop in parentheses. (This example is not in the course folder either.)
package main
import "fmt"
func main() {
for (i := 0; i < 3; i++) {
fmt.Println(i)
}
}$ go run qavs/main.go
# command-line-arguments
qavs/main.go:6:9: syntax error: unexpected :=, expected )Line 6, column 9: unexpected :=, expected ). Inside the parentheses Go expected a simple condition, not :=.
Fix: remove the parentheses: for i := 0; i < 3; i++ {. Only in a condition-only loop are parentheses not an
error: for (n < 100) { works, but gofmt turns it into for n < 100 { anyway.
5. An unused label. (Not in the course folder.) Here break has no label, and qidiruv is not used anywhere:
package main
import "fmt"
func main() {
sonlar := []int{4, 7, -1}
qidiruv:
for _, s := range sonlar {
if s < 0 {
break
}
fmt.Println(s)
}
}$ go run ortiqcha/main.go
# command-line-arguments
ortiqcha/main.go:7:1: label qidiruv defined and not usedlabel qidiruv defined and not used. Just like an unused variable, Go treats this as an error. Fix: delete the
label (here break is not inside a switch, so no label is needed) or use it: break qidiruv.
6. Writing range 3 in an old module. (Not in the course folder; a separate module with go 1.21 in its
go.mod.)
package main
import "fmt"
func main() {
for i := range 3 {
fmt.Print(i, " ")
}
fmt.Println()
}$ cd eskirange && go run .
# eskirange
./main.go:6:17: cannot range over 3 (untyped int constant): requires go1.22 or later (-lang was set to go1.21; check go.mod)cannot range over 3 … requires go1.22 or later (-lang was set to go1.21; check go.mod): the language version is
set to go1.21, and this needs Go 1.22 or later. The message even tells you where to look. Fix: raise the go
line in go.mod to 1.22 or higher, or write a three-part loop.
7. Thinking that a variable created before the loop is new on each step. The Go 1.22 rule applies only to a
variable declared by the loop itself. Here j is created before the loop with var j int, and the for only
assigns to it with = (this example is not in the course folder; it was run in a go 1.26 module):
package main
import "fmt"
func main() {
var navbat []*int
var j int
for j = 0; j < 3; j++ {
navbat = append(navbat, &j)
}
for _, p := range navbat {
fmt.Print(*p, " ")
}
fmt.Println()
}$ go run tashqi/main.go
3 3 3 One j, and all three addresses point to it. The loop stopped when j became 3, so it prints 3 3 3. Fix:
create j in the for itself: for j := 0; j < 3; j++. Then it is a loop variable and the result is 0 1 2.
Check yourself
Answer first, then open the answer.
1. How do you write a while loop in Go?
Answer
With for, keeping only the condition: for n < 100 { … }. Go has no while keyword.
2. What does this code print?
for i := range 4 {
fmt.Print(i, " ")
}
fmt.Println()Answer
0 1 2 3. range 4 starts at 0 and does not include 4 itself.
$ go run savol1/main.go
0 1 2 3 3. What does this code print? A) 0 · B) 0 1 2 · C) 0 2
for i := 0; i < 3; i++ {
switch i {
case 1:
break
}
fmt.Print(i, " ")
}
fmt.Println()Answer
B: 0 1 2. break leaves only the switch, and fmt.Print comes after the switch, so it runs on every
step. The loop does not stop either.
$ go run savol2/main.go
0 1 2 4. Does fallthrough check the condition of the next case?
Answer
No. It goes into the body of the next case without checking the condition. That is why in tanlov “ish kuni”
was added for 1, even though 1 is not in the list 2, 3, 4, 5.
5. The same code printed a.uz b.uz c.uz in one module and c.uz c.uz c.uz in another. Where do you look?
Answer
At the go line in go.mod. If it is below 1.22, the loop has one variable, and all the saved addresses point to
it. If it is 1.22 or higher, a variable declared by the loop itself is new on each step.
6. From GO-1.02: var x int8 = 127, then x++. What does fmt.Println(x) print?
Answer
-128. An int8 cannot hold a number bigger than 127, and the variable “wraps around” to the smallest value
without any error (overflow).
$ go run overflow/main.go
-128(The programs in questions 2, 3 and 6 are not in the course folder: they were run separately.)
Homework
Tasks at four levels. All files and answers are in the lesson folder on GitHub: lessons/005-for-switch . Answers: the homework/ folder. Try it yourself first.
🟢 Easy: write FizzBuzz from 1 to 15 with a switch with no expression: if the number divides by 3, print
Fizz; by 5, Buzz; by both, FizzBuzz; otherwise the number itself.
Answer
homework/oson/main.go. A switch with no expression runs the first case that is true, so
case i%15 == 0 must come first. Otherwise, for 15, i%3 == 0 runs earlier and prints Fizz.
$ go run ./homework/oson
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 🟡 Medium: with a switch, turn each digit of a number into an Uzbek word: 2026 → ikki nol ikki olti
(“two zero two six”).
Answer
homework/orta/main.go. strconv.Itoa turns the number into a string, range walks over its runes, and the
switch turns each digit ('0', '1', …) into a word. default handles unexpected characters, and case '-'
handles negative numbers.
$ go run ./homework/orta
2026: ikki nol ikki olti
1990: bir toʻqqiz toʻqqiz nol
-7: minus yetti 🟠 Hard: in a two-dimensional table (a list of lists), find the first 0 and leave both loops with a label.
Answer
homework/qiyin/main.go. The outer loop walks over the rows, the inner loop over the numbers in a row. A plain
break would leave only the inner loop, and the outer loop would look for a 0 again in the next row. That is why
the outer loop has the label tashqi: (“outer”) and the code says break tashqi.
$ go run ./homework/qiyin
birinchi 0: qator 1, ustun 1🔴 Guru: fix the bug in eski/ without touching go.mod. There are three ways.
Answer
homework/guru/ is a separate module with go 1.21 in its go.mod (the old rule).
d := d: a new variable is created inside the loop, so each address points to its own copy. This is how code was written before Go 1.22; in ago 1.22+module this line is not needed, andgo fix(the Go command that updates old code) removes it.&domenlar[i]: the address of the slice element itself, not of the loop variable. There is no copy here at all.- The line
//go:build go1.22at the top of a file raises the language version for that file: even if the module stays atgo 1.21, this file gets a newdon each step. More on this: GO-1.16.
$ cd homework/guru && go run .
a.uz b.uz c.uz ← d := d
a.uz b.uz c.uz ← &domenlar[i]$ cd homework/guru && go run ./buildtag
a.uz b.uz c.uz ← //go:build go1.22Sources
- The official Go rules (Go spec): Keywords , For statements , For range , Switch statements , Break statements , Labeled statements
- Go 1.22 Release Notes (
rangeover integers, a new variable on each iteration), Go 1.23 Release Notes (rangeover functions) - David Chase, Russ Cox: Fixing For Loops in Go 1.22 (Go blog, 2023), LoopvarExperiment
- Russ Cox, discussion #56010: redefining for loop variable semantics (the test inside Google: ~100,000 tests, 58 failed)
- RISKS Digest 9.69 (AT&T, 1990)
- Mozilla Bugzilla 1619047 (incident report), 1619179 (revoked certificates); Let’s Encrypt: 2020.02.29 CAA Rechecking Bug
- About Let’s Encrypt , Let’s Encrypt: CAA , RFC 8659: DNS CAA
- Java’s new
switch: JEP 361: Switch Expressions (Java 14) - Donovan, Kernighan, The Go Programming Language, §1.8 (sample chapter ):
fallthroughis rarely used - Bill Kennedy, For Range Semantics (Ardan Labs, 2017; written before Go 1.22)
- The list of staticcheck checks (SA4006, SA4011, S1023)
- All results were produced with
go1.26.8 linux/amd64and staticcheck 2026.2.1, on 2026-11-26.
Video and code
▶️ The video is coming soon. This page teaches the whole lesson, so you don’t have to wait for it.
💻 Code and homework answers on GitHub
← Previous lesson: GO-1.04 · Next lesson: GO-1.06 → · All lessons
comments