Constants and iota: not JS const, time.Sleep(2) and the silent enum bug
Why Go const is not JS const, where an untyped constant gets its type, why time.Sleep(2) = 2 ns and how a status added mid-iota breaks the database.
🌐 Oʻzbekcha · Русский · English
Lesson GO-1.03 · Go: 0 → Guru · ▶️ Watch the video on YouTube · 💻 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
Paid orders are stored in the database with status = 2. Someone added one new status in the middle of the status
list in the Go code. The compiler is silent. What do those orders look like the next day? The answer is in the
second half of the lesson, and it follows from one rule of Go constants.
One idea: in Go, const is a value known at compile time, and a constant without a written type (an untyped
constant) takes its type from the place where it is used: that is why time.Sleep(2) asks for two nanoseconds.
iota takes its value from the position of the declaration in a const block, so a status added in the middle of
the list silently changes the meaning of the numbers in the database.
By the end of the lesson you will be able to:
- tell Go
constfrom JavaScriptconst: which expression can be a constant, and which one givesis not constant; - explain why
time.Sleep(2)is not 2 seconds and not 2 ms but 2 nanoseconds, and write the right time with2 * time.Secondandtime.Duration(n) * time.Second; - write a status list with
iotaand add a new status without breaking the numbers in the database.
Today’s three core new words:
| Word | Plain meaning | English term |
|---|---|---|
const | a name whose value is known at compile time: only a number, a string or a bool | constant |
| untyped constant | a constant without a written type: it takes its type from the place where it is used | untyped constant |
iota | the index of a declaration in a const block, from 0 | iota |
Two helper words also appear: time.Duration (a span of time, a count of nanoseconds) and a new type
(type Duration int64: based on int64, but a separate type). There are also two phrases, default type and
typed constant; the untyped constant section explains them.
Before you start
- GO-X.01 · A 20-line HTTP API: the first Go service and one binary:
go run, reading a compiler error infile:line:columnorder. - GO-X.02 · Types exist at runtime too: “2” + 2 is 22 in JS, a compile error in Go: static types;
no implicit conversion (an
intvariable does not go into afloat64);:=picksintfor an integer; the zero value. - GO-X.03 · No try/catch: the error value and defer: the
errorvalue. You need it only in the 🟡 homework. - GO-1.02 · Types and overflow: Go refuses, but x++ silently wraps around: the limit of
int8, overflow in a variable wraps silently, but a constant that does not fit is a compile error; the conversionint8(big). - You can copy the Go programs to go.dev/play and run them there. If you downloaded the course
code, open a terminal in the lesson folder (
lessons/003-const-iota): every command works from there. - The comparison files are in the
anchors/folder. For them you neednode,python3,php(8.4) andtsc(TypeScript 5.9.3). Iftscis not installed:npx -p typescript@5.9.3 tsc --strict --types --lib es2022,dom anchors/enum1.ts. The.jsfiles thattscmakes appear insideanchors/. notconst/,untyped-xato/,duration-type/,config/,sinov/andaddr/do not compile on purpose. That is whygo vet ./...reports errors for them: run each folder on its own.
First, one question from the previous lesson:
var x int8 = 127
x += 3
fmt.Println(x)What does it print? A) 130 · B) 127 · C) -126 · D) the program stops
Answer
C: -126. x is a variable, its value is computed while the program runs. After 127, the int8 crosses its
limit and silently wraps around: 127 → −128 → −127 → −126. If you chose “130”, you thought of a number without
limits, as in Python. If you chose “127”, you thought Go holds the number at the limit. If you chose “the program
stops”, you thought overflow causes a panic: it does not.
package main
import "fmt"
func main() {
var x int8 = 127
x += 3 // 127 → −128 → −127 → −126: jim aylanadi (02-dars)
fmt.Println(x)
}$ go run eslash/main.go
-126A variable wraps around silently. A constant, however, Go checks at compile time: var x int8 = 128 did not compile
at all. That error message contained the words untyped int constant. Today we open up exactly these words.
const: not the const of JavaScript
Today: three Go concepts, each next to something you know: const ↔ JS const, untyped constant ↔
time.Sleep(2), iota ↔ TypeScript enum. We start with the first.
In JavaScript, const freezes only the name: you cannot bind it to another value. The value itself is computed
at run time, for example from Date.now(). And the inside of an object still changes:
// JS const faqat nomni qayta bogʻlashni taqiqlaydi
const cfg = { port: 80 };
cfg.port = 81; // ✅ obyekt ichi oʻzgaradi
console.log(cfg.port); // 81
const start = Date.now(); // ✅ qiymat ishlash paytida olinadi
console.log(typeof start); // number$ node anchors/const.js
81
numberPython has no constants at all. A name in capital letters is just a convention (PEP 8), and overwriting it works:
# Python'da konstanta faqat kelishuv (katta harfli nom)
MAX_RETRIES = 3
MAX_RETRIES = 4 # ✅ ishlaydi
print(MAX_RETRIES) # 4$ python3 anchors/const.py
4In Go, const is something else. Its value must be known at compile time, and it can only be a number (a rune
too), a string or a bool. A constant expression contains only constants and operators, not an ordinary function
call. (Some built-in functions such as len("abc"), min and max are an exception when used with constants.)
The benefit: mistakes like var x int8 = 128 from the previous lesson are caught before the program starts.
| Language | What const freezes | When the value is known | Who checks |
|---|---|---|---|
| JavaScript | the name (cannot be rebound) | at run time (Date.now()) | the runtime |
| Python | nothing: a capitalized name is a convention | at run time | nobody |
| PHP | the name and the value | at compile time | PHP, before the file runs |
| Go | the name and the value | at compile time | the compiler |
Now three lines. Ten megabytes in bytes, the square root of two and the current time (like Date.now() in JS):
const maxSize = 10 * 1024 * 1024
const root2 = math.Sqrt(2)
const start = time.Now()Which of them compile? A) all three · B) maxSize and root2 · C) only maxSize · D) none
Answer
C: only maxSize. 10 * 1024 * 1024 contains only constants and the * operator, and the compiler computes it
itself. The result of math.Sqrt(2) never changes, but it is a function call: Go computes it at run time. And
time.Now() returns a different value every time. If you chose “all three”, you thought Go const works like JS
const. If you chose “maxSize and root2”, you thought “if the result does not change, it is a constant”: Go
looks at the expression itself, not at the result.
The full program, notconst/main.go:
package main
import (
"fmt"
"math"
"time"
)
func main() {
const maxSize = 10 * 1024 * 1024 // faqat konstantalar va operatorlar: kompilyator hisoblaydi
const root2 = math.Sqrt(2) // ataylab xato: funksiya chaqiruvi — natija ishlash paytida
const start = time.Now() // ataylab xato: time.Now() faqat ishlash paytida maʼlum
fmt.Println(maxSize, root2, start)
}| Line | Code | What it does |
|---|---|---|
| 3–7 | import ( "fmt" "math" "time" ) | imports the packages fmt (printing), math (math functions) and time (time) |
| 10 | const maxSize = 10 * 1024 * 1024 | a constant expression: 10,485,760, computed by the compiler ✅ |
| 11 | const root2 = math.Sqrt(2) | a function call: the result exists only at run time ❌ |
| 12 | const start = time.Now() | the current time: known only at run time ❌ |
| 13 | fmt.Println(maxSize, root2, start) | would print all three |
$ go run notconst/main.go
# command-line-arguments
notconst/main.go:11:16: math.Sqrt(2) (value of type float64) is not constant
notconst/main.go:12:16: time.Now() (value of struct type time.Time) is not constantTwo lines, both say is not constant. notconst/main.go:11:16 is line 11, column 16, the place where math.Sqrt(2)
stands. In parentheses Go gives its type: value of type float64. time.Now() returns a time.Time struct.
Line 10 has no error.
PHP’s const works the same way: if you write the function time(), the file does not run at all.
<?php
// PHP const: Go kabi, faqat kompilyatsiya paytida maʼlum ifoda
const MAX_SIZE = 10 * 1024 * 1024; // ✅
echo MAX_SIZE, "\n";
const START = time(); // ❌ Fatal error: Constant expression contains invalid operations$ php anchors/const.php
Fatal error: Constant expression contains invalid operations in …/anchors/const.php on line 5(The full path in the output is shortened to …: it depends on the folder on your computer.) The echo on line 4
did not run either: PHP checks the whole file before running it. In both Go and PHP, a value known only at run time
goes into an ordinary variable: in Go, start := time.Now().
Untyped constant: the type comes from the place of use
You know this from the lesson on types: you cannot put an int variable into a float64, Go has no implicit
conversion. untyped-xato/main.go:
package main
import "fmt"
func main() {
n := 100 // oʻzgaruvchi: turi int
var b float64 = n // ataylab xato: int oʻzgaruvchini float64 ga yashirin konversiya yoʻq
fmt.Println(b)
}$ go run untyped-xato/main.go
# command-line-arguments
untyped-xato/main.go:7:18: cannot use n (variable of type int) as float64 value in variable declarationcannot use n (variable of type int) as float64 value: the variable n has type int and cannot be used as a
float64 value. The := on line 6 gave n the type int, and that does not change.
A constant without a written type, however, has no type yet. This is called an untyped constant. It takes its
type from the place where it is used: int8 on one line, float64 on another. untyped/main.go:
package main
import "fmt"
func main() {
const yuz = 100 // untyped constant: turi hali yoʻq
var a int8 = yuz // bu yerda int8 boʻldi
var b float64 = yuz // bu yerda float64 boʻldi
m := yuz // tur aytilmagan joy → default type: int (butun son konstantasi uchun)
fmt.Println(a/8, b/8) // int8: kasr tashlanadi, float64: qoladi
fmt.Printf("%T\n", m) // int
}| Line | Code | What it does |
|---|---|---|
| 6 | const yuz = 100 | yuz (“a hundred”, 100) is an untyped constant: no type is written |
| 7 | var a int8 = yuz | here yuz becomes int8 |
| 8 | var b float64 = yuz | here it becomes float64: no error like in untyped-xato |
| 9 | m := yuz | := names no type: an integer constant gets its default type, which is int |
| 10 | fmt.Println(a/8, b/8) | int8 division drops the fraction (12), float64 keeps it (12.5) |
| 11 | fmt.Printf("%T\n", m) | %T prints the type of the value; \n is a new line |
$ go run untyped/main.go
12 12.5
intOne yuz, three different types:
| Where it is used | Type of yuz at that place | Why |
|---|---|---|
var a int8 = yuz | int8 | the variable’s type is written |
var b float64 = yuz | float64 | the variable’s type is written |
m := yuz | int | no type is named → default type |
The default type is the type Go picks where no type is named (:=, fmt.Println): int for an integer,
float64 for a floating-point number, rune for 'a'. The opposite of an untyped constant is a typed constant:
a constant with a written type (const b int = 3). It is as strict as a variable; we see this in the “Check”
section.
TypeScript has something close to this. The type of const a = 3 is not number but 3 (a literal type). If you
give it to a let, the type widens to number:
// TS: const a = 3 → literal type 3; let b = a → number ga kengayadi ("widening")
const a = 3
let b = a
const ok: 3 = a
const bad: 3 = b // TS2322: Type 'number' is not assignable to type '3'.$ tsc --strict anchors/literal.ts
anchors/literal.ts(5,7): error TS2322: Type 'number' is not assignable to type '3'.Line 4 passed: the type of a is still 3. On line 5, b is already number. Go’s untyped constant and default
type are the same idea. The difference: TypeScript types are erased after compilation, while in Go the chosen type
stays at run time too.
time.Sleep(2): seconds, milliseconds or nanoseconds?
You feel this rule most when you work with time. In Python, time.sleep(2) waits two seconds:
import time
t = time.monotonic()
time.sleep(2) # soniya
print(round(time.monotonic() - t, 1)) # 2.0$ python3 anchors/sleep.py
2.0In Node’s setTimeout, 2 means two milliseconds:
const t = Date.now();
setTimeout(() => console.log(Date.now() - t), 2); // millisekund → 2$ node anchors/sleep.js
2In Go, the parameter of time.Sleep is a time.Duration: func Sleep(d Duration). time.Duration counts a span
of time in nanoseconds (billionths of a second).
type Duration int64: a new type, not an alias
The time package declares it as type Duration int64. In TypeScript, type Ms = number is only an alias: any
number goes into it.
// TS: type Ms = number — faqat taxallus (alias): istalgan number oʻtadi
type Ms = number
function sleep(ms: Ms) {}
const n: number = 2
sleep(n) // ✅ xato yoʻq. Go'da type Duration int64 esa alohida tur: int oʻtmaydi$ tsc --strict anchors/alias.tstsc printed nothing: no error. In Go, type creates a new type. Duration is based on int64, but you cannot
put an int variable into a Duration. duration-type/main.go:
package main
import (
"fmt"
"time"
)
func main() {
// time paketida: type Duration int64 — asosi int64, lekin alohida tur
var n int = 2
var d time.Duration = n // ataylab xato: int → time.Duration yashirin oʻtmaydi
fmt.Println(d)
}$ go run duration-type/main.go
# command-line-arguments
duration-type/main.go:11:24: cannot use n (variable of type int) as time.Duration value in variable declarationLine 11, column 24: n. The message is the same as in untyped-xato, only with time.Duration instead of
float64.
TypeScript type Ms = number | Go type Duration int64 | |
|---|---|---|
| What it is | an alias | a new type |
| Passing a plain number | sleep(n) ✅ | var d time.Duration = n ❌ |
| At run time | no type | the type exists |
Predict
Now in Go there is a 2 inside time.Sleep:
time.Sleep(2) // func Sleep(d Duration)How long does the program ask to wait? A) 2 seconds · B) 2 milliseconds · C) 2 nanoseconds · D) the type does not match, a compile error
Answer
C: 2 nanoseconds, with no error. 2 is an untyped constant. It takes the type of the Sleep parameter, which is
time.Duration, and a Duration counts nanoseconds. If you chose “2 seconds”, you carried over the Python rule.
“2 milliseconds” is the setTimeout rule. If you chose “a compile error”, you remembered the error in
duration-type: there n was a variable with a type, here 2 is a constant without one.
sleep2/main.go:
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
time.Sleep(2) // 2 soniya? 2 millisekund?
fmt.Println(time.Duration(2), time.Since(start) < time.Millisecond)
}| Line | Code | What it does |
|---|---|---|
| 9 | start := time.Now() | remembers the start time |
| 10 | time.Sleep(2) | 2 → time.Duration: asks for 2 nanoseconds |
| 11 | time.Duration(2) | prints 2 as a Duration: Println writes it with its unit |
| 11 | time.Since(start) < time.Millisecond | did less than 1 millisecond pass? true or false |
$ go run sleep2/main.go
2ns true2ns is the requested time. true means Sleep returned in less than a millisecond. Sleep waits at least d, and
the exact time depends on the OS: while the lesson was prepared, 1000 calls of time.Sleep(2) returned in 0.3–14
microseconds. Both the compiler and go vet are silent. staticcheck SA1004
does catch such a small constant in time.Sleep.
The fix: 2 * time.Second
For two seconds, write 2 * time.Second. kutish/main.go:
package main
import (
"fmt"
"time"
)
func main() {
time.Sleep(2) // untyped 2 → time.Duration: 2 nanosekund soʻraydi
var d time.Duration = 2
fmt.Println(d) // Duration birligi bilan chiqadi: 2ns
d = 2 * time.Second // time.Second: typed constant, turi Duration (1 000 000 000 ns)
fmt.Println(d) // 2s
time.Sleep(d) // 2 soniya kutadi
}| After line | d (time.Duration) | On screen | Note |
|---|---|---|---|
| 9 | — | untyped 2 → Duration: asks for 2 ns | |
| 10 | 2 | d = 2 nanoseconds | |
| 11 | 2 | 2ns | Println prints a Duration with its unit |
| 12 | 2,000,000,000 | time.Second = 1,000,000,000 ns | |
| 13 | 2,000,000,000 | 2s | |
| 14 | 2,000,000,000 | waits 2 seconds ✅ |
$ go run kutish/main.go
2ns
2s(After 2s the program waits 2 more seconds, then ends.) time.Second is a typed constant: its type is
Duration, its value is one billion nanoseconds. The time package writes it like this:
Nanosecond Duration = 1, Microsecond = 1000 * Nanosecond, …, Second = 1000 * Millisecond. In
2 * time.Second the 2 is untyped, it adapts to Duration, and the result is a Duration too.
Seconds from the config: n * time.Second
Now a situation from real work: the number of seconds to wait comes from the config or env. Just now,
2 * time.Second worked.
n := 2
time.Sleep(n * time.Second)What happens this time? A) it waits 2 seconds · B) it waits 2 nanoseconds · C) a compile error
Answer
C: a compile error. := gave n its default type, int. Now n is a variable of type int, and Go does not
turn an int into a Duration silently. The literal 2, on the other hand, was untyped and adapted to Duration.
If you chose “2 seconds”, you thought n adapts like 2. If you chose “2 nanoseconds”, you carried the
time.Sleep(2) trap over to this case.
package main
import (
"fmt"
"time"
)
func main() {
n := 2 // masalan, config yoki env'dan oʻqilgan soniyalar soni: tur = int
time.Sleep(n * time.Second) // ataylab xato: int × time.Duration
fmt.Println("tayyor")
}$ go run config/main.go
# command-line-arguments
config/main.go:10:13: invalid operation: n * time.Second (mismatched types int and time.Duration)Line 10, column 13. invalid operation: n * time.Second (mismatched types int and time.Duration): the operation is
invalid because the types int and time.Duration do not match.
The fix: time.Duration(n) converts n to Duration explicitly (a conversion, like int8(big) in
GO-1.02), then * time.Second. The time package’s own documentation shows exactly this form.
config-fix/main.go:
package main
import (
"fmt"
"time"
)
func main() {
n := 2
d := time.Duration(n) * time.Second // konversiya: int → time.Duration
fmt.Println(d)
time.Sleep(d) // 2 soniya kutadi
}$ go run config-fix/main.go
2s(This program also waits 2 seconds after 2s.) Be careful: if you write only the conversion and forget the
multiplication, you get 2 nanoseconds again. wrongfix/main.go:
package main
import (
"fmt"
"time"
)
func main() {
n := 2
fmt.Println(time.Duration(n) * time.Second) // 2s — toʻgʻri
fmt.Println(time.Duration(n)) // 2ns — notoʻgʻri tuzatish: birlik yoʻq
}$ go run wrongfix/main.go
2s
2ns| Code | n = 2 | Result |
|---|---|---|
n * time.Second | int × Duration | compile error |
time.Duration(n) | 2 ns | no error, but wrong ❌ |
time.Duration(n) * time.Second | 2 × 1,000,000,000 ns | 2s ✅ |
staticcheck SA1004 does not catch time.Sleep(time.Duration(n)): it looks only at constants. If the config holds
text such as "2s", use time.ParseDuration("2s") (similar to ms('2s') from npm).
Why is Go this strict? Go left out implicit numeric conversion on purpose (Go FAQ). Untyped constants keep numeric
literals convenient even with this strictness: 2 * time.Second or var b float64 = 100 need no conversion (Rob
Pike, Constants).
Check: untyped a and typed b
Two constants: we wrote no type for a, and int for b. Then we multiply both by time.Second:
const a = 3
const b int = 3
x := a * time.Second
y := b * time.SecondWhich line does not compile? A) neither · B) x · C) y · D) both
Answer
C: the y line. A typed constant is as strict as a variable: b is now an int, and you cannot multiply an
int by a Duration. The untyped a adapted to Duration. If you chose “neither”, you thought every constant
adapts. If you chose “x” or “both”, you thought a constant becomes int like n: an untyped constant gets its
default type only where no type is named.
package main
import (
"fmt"
"time"
)
func main() {
const a = 3 // untyped
const b int = 3 // typed: turi int
x := a * time.Second
y := b * time.Second // ataylab xato: int × time.Duration
fmt.Println(x, y)
}$ go run sinov/main.go
# command-line-arguments
sinov/main.go:12:7: invalid operation: b * time.Second (mismatched types int and time.Duration)Only line 12. There is one rule: an untyped constant takes its type from the place where it is used, while a typed
constant carries its own type everywhere. That is also why int8(127) + 1 in GO-1.02 was rejected:
int8(127) is a typed constant, and by the Go spec the value of a typed constant must always fit its type. 128 does
not fit in an int8.
TypeScript enum and Go’s iota
Now back to the question from the start. In TypeScript, an enum assigns the numbers itself: Unknown 0, New 1,
Paid 2.
enum Status { Unknown, New, Paid }
console.log(Status.New, Status.Paid) // 1 2$ tsc anchors/enum1.ts && node anchors/enum1.js
1 2Go has no enum keyword. Instead, we use our own type and iota in a const block. holat/main.go (“holat”
means status):
package main
import "fmt"
type Holat int // time.Duration kabi: asosi int boʻlgan alohida tur
const (
Nomalum Holat = iota // 0: zero value — holat berilmagan
Yangi // 1: faqat nom → oldingi ifoda "Holat = iota" takrorlanadi
Tolangan // 2
)
func main() {
var h Holat // zero value
fmt.Println(Yangi, Tolangan, h == Nomalum)
}| Line | Code | What it does |
|---|---|---|
| 5 | type Holat int | our own type, like time.Duration: based on int, but a separate type |
| 7 | const ( | a const block: several constants inside one pair of parentheses |
| 8 | Nomalum Holat = iota | Nomalum (“unknown”). iota is the index of the declaration in the block, from 0. Nomalum = 0 |
| 9 | Yangi | (“new”) only a name: Go repeats the previous expression Holat = iota, iota = 1 |
| 10 | Tolangan | (“paid”) repeated again, iota = 2 |
| 14 | var h Holat | no value given: the zero value, 0 |
| 15 | fmt.Println(Yangi, Tolangan, h == Nomalum) | two numbers and a comparison |
$ go run holat/main.go
1 2 trueThe result is the same as in TypeScript: 1 2. The compiler reads the block like this:
| Line | Written | What Go sees | iota | Value |
|---|---|---|---|---|
| 8 | Nomalum Holat = iota | Nomalum Holat = iota | 0 | 0 |
| 9 | Yangi | Yangi Holat = iota | 1 | 1 |
| 10 | Tolangan | Tolangan Holat = iota | 2 | 2 |
Comments and empty lines are not counted: iota counts only declarations. In every new const block it starts
again from 0.
This type is not closed: Holat(42) also compiles. Go checks only the type, not whether the value is in the list
(the exhaustive linter checks that every status is handled).
Why is 0 exactly Nomalum? A variable with no status holds the zero value, 0 (line 14). If 0 were Yangi, an
order whose status was forgotten would look new. So we leave 0 to Nomalum. The style guide of Protobuf (the schema
format of gRPC) asks for the same: the first value is …_UNSPECIFIED = 0.
A status added in the middle of the list
Now we write the change from the start. Yesterday a paid order was written to the database with the number 2. Today
someone added a new status, Bekor (“cancelled”), and wrote it after Yangi. We compare the stored 2 with
Tolangan and Bekor. xato/main.go:
package main
import "fmt"
type Holat int
const (
Nomalum Holat = iota
Yangi
Bekor // yangi holat oʻrtaga qoʻshildi
Tolangan
)
func main() {
var saqlangan Holat = 2 // kecha bazaga yozilgan: oʻshanda 2 = Tolangan edi
fmt.Println(saqlangan == Tolangan, saqlangan == Bekor)
}Line 10 is the new status. Line 15 holds yesterday’s 2, line 16 makes two comparisons.
What appears on the screen? A) true false · B) false true · C) a compile error. Count the
declarations yourself.
Answer
B: false true. Bekor is at position 2, so now Bekor = 2 and Tolangan = 3. If you chose “true false”,
you thought the number of Tolangan was fixed: iota takes the number from the position. If you chose “a compile
error”, you thought Go notices that the numbers changed: it knows nothing about the database.
$ go run xato/main.go
false trueBoth compiling and running go without errors. But now 2 is Bekor:
| Name | Yesterday | Today |
|---|---|---|
Nomalum | 0 | 0 |
Yangi | 1 | 1 |
Bekor | — | 2 |
Tolangan | 2 | 3 |
status = 2 in the database | paid ✅ | cancelled 💥 |
Yesterday’s paid orders look cancelled. A TypeScript enum gives exactly the same result:
enum Status { Unknown, New, Cancelled, Paid } // Cancelled oʻrtaga qoʻshildi
const saved: number = 2 // kecha bazaga yozilgan: oʻshanda 2 = Paid
console.log(saved === Status.Paid, saved === Status.Cancelled) // false true$ tsc anchors/enum2.ts && node anchors/enum2.js
false trueThe fix
The rule: the meaning of a number that goes to a database or into JSON must never change. There are three ways:
- Write the numbers by hand. Each status states its own number, and a new one goes to the end.
- If you keep
iota, add a new status only at the end and delete none (in place of a deleted status you can leave_, see question 3 in “Check yourself”). - Store the name, not the number: write
"paid"to the database, like a stringenumin TypeScript. You do this in the 🟡 homework.
The first way, tuzatish/main.go:
package main
import "fmt"
type Holat int
const ( // bazaga saqlanadigan raqamlar qoʻlda yoziladi va hech qachon oʻzgarmaydi
Nomalum Holat = 0
Yangi Holat = 1
Tolangan Holat = 2
Bekor Holat = 3 // yangi holat roʻyxat oxiriga
)
func main() {
var saqlangan Holat = 2
fmt.Println(saqlangan == Tolangan, saqlangan == Bekor)
}$ go run tuzatish/main.go
true falseWith numbers written by hand, the stored 2 is Tolangan again. Protobuf also makes you write each value’s number
by hand, and to mark a deleted number as reserved, so it is never reused.
Going deeper (optional): 0.1 + 0.2 == 0.3
The famous JavaScript question:
$ node -p '0.1 + 0.2 === 0.3'
false(This command is not a file in the course folder: the code is in the command itself.) What do we get in Go with constants that have no written type?
const a, b = 0.1, 0.2
fmt.Println(a+b == 0.3)A) true · B) false
Answer
A: true. Untyped constant expressions are computed exactly (Go spec: “evaluated exactly”): the sum is exactly
0.3, nothing is rounded. If you chose “false”, you carried over the JS rule: it is true for float64.
package main
import "fmt"
func main() {
const a, b = 0.1, 0.2 // untyped: aniq hisoblanadi
fmt.Println(a+b == 0.3)
const c, d float64 = 0.1, 0.2 // typed: float64 ga yaxlitlangan
fmt.Println(c+d == 0.3)
x, y := 0.1, 0.2 // float64 oʻzgaruvchilar
fmt.Println(x+y == 0.3, x+y)
}$ go run float/main.go
true
false
false 0.30000000000000004| Lines | What | Result |
|---|---|---|
| 6–7 | untyped constants: exact computation | true |
| 9–10 | float64 type written: each one is rounded to float64 | false |
| 12–13 | float64 variables: like JavaScript | false 0.30000000000000004 |
Common mistakes
1. Adding a status in the middle of an iota list. The most classic mistake of this topic. No error, no warning:
every number after it shifts by one, and the 2 in the database now means another status. The full example is in
the section “A status added in the middle of the list”. Fix: write the numbers that go to a database or into JSON
by hand, or add a new status only at the end, or store the name.
2. Thinking time.Sleep(2) means two seconds. The compiler is silent: 2 is untyped, it becomes a Duration
and asks for 2 nanoseconds. The example is in the “time.Sleep(2)” section. Fix: always write the unit:
2 * time.Second, 500 * time.Millisecond. staticcheck SA1004 catches this.
3. Multiplying an int variable by time.Second. n * time.Second →
mismatched types int and time.Duration (config/main.go). Fix: time.Duration(n) * time.Second. Not just
time.Duration(n): that is 2 nanoseconds (wrongfix/main.go).
4. Making a run-time value a const. const start = time.Now() →
time.Now() (value of struct type time.Time) is not constant (notconst/main.go). Fix: an ordinary variable:
start := time.Now(). const is only for numbers, strings and bools known at compile time.
5. Taking the address of a constant. This mistake is not in the video, but it is in the course folder,
addr/main.go:
package main
import "fmt"
const Port = 8080
func main() {
fmt.Println(&Port) // ataylab xato: konstantaning xotirada manzili yoʻq
}$ go run addr/main.go
# command-line-arguments
addr/main.go:8:15: invalid operation: cannot take address of Port (untyped int constant 8080)cannot take address of Port: you cannot get the address of Port (a server port, 8080). & gives the address of a value in memory
(pointers come in later lessons). By Go’s rules, & applies only to a value that has its own place in memory, like a
variable (addressable), and a constant is not one. Fix: put it into a variable first (p := Port, then &p).
Since Go 1.26, new(Port) also works: it creates a new variable holding a copy of the value.
Check yourself
Answer first, then open.
1. What is the main difference between JavaScript const and Go const?
Answer
The value of a Go const must be known at compile time (only a number, a string or a bool; not a function call).
JavaScript const freezes only the name, and the value is computed at run time.
2. If n := 2, how long does time.Sleep(time.Duration(n)) ask to wait?
Answer
2 nanoseconds. time.Duration(n) changes only the type, it adds no unit. For two seconds you need
time.Duration(n) * time.Second.
3. If we delete Yangi from the iota list Nomalum, Yangi, Tolangan, Bekor, what does the 2 in the database
mean? What does ochirish/main.go print?
package main
import "fmt"
type Holat int
const (
Nomalum Holat = iota
// Yangi oʻchirildi → keyingilarning raqami bittaga kamaydi
Tolangan // endi 1
Bekor // endi 2
)
const (
Nomalum2 Holat = iota
_ // Yangi oʻchirildi, lekin raqami band qoldi
Tolangan2 // 2
Bekor2 // 3
)
func main() {
var saqlangan Holat = 2 // kecha: 2 = Tolangan
fmt.Println(saqlangan == Tolangan, saqlangan == Bekor)
fmt.Println(saqlangan == Tolangan2, saqlangan == Bekor2)
}Answer
In the first block, 2 is now Bekor, because the following numbers shift by one: Tolangan = 1, Bekor = 2. In
the second block, a _ (the blank name) stands where the deleted Yangi was: it keeps the number taken, so
Tolangan2 is 2 again.
$ go run ochirish/main.go
false true
true false4. From GO-1.02: the error message for var x int8 = 128 contained the words (untyped int
constant). And x++ silently wrapped from 127 to −128. Explain the difference with today’s words.
Answer
128 is an untyped constant: it takes the type int8 from the place where it is used, the variable declaration. Go
does this at compile time and sees that 128 does not fit in an int8. x++ is an operation on a variable: it
happens at run time and wraps around silently.
Homework
Starter files and answers are in the lesson folder on GitHub:
lessons/003-const-iota
(the uyga/ folder). The commands work from the lesson folder.
🟢 Easy (uyga/oson/main.go): add a status Qaytarilgan (“refunded”) for orders whose money was returned, so
that 2 (Tolangan) and 3 (Bekor) in the database keep their meaning.
// 🟢 Vazifa: pul qaytarilgan buyurtmalar uchun yangi holat — Qaytarilgan — qoʻshing.
// Shart: bazada allaqachon saqlangan raqamlar (2 = Tolangan, 3 = Bekor) maʼnosini saqlashi kerak.
// Avval natijani taxmin qiling, keyin: go run uyga/oson/main.go
// Kutilgan natija (toʻgʻri yechimda): true false false
package main
import "fmt"
type Holat int
const (
Nomalum Holat = iota
Yangi
Tolangan
Bekor
// VAZIFA: Qaytarilgan holatini shunday qoʻshingki, yuqoridagi raqamlar oʻzgarmasin
)
func main() {
var saqlangan Holat = 2 // kecha bazaga yozilgan: 2 = Tolangan
fmt.Println(saqlangan == Tolangan, saqlangan == Bekor, saqlangan == Qaytarilgan)
}The starter file does not compile yet, because Qaytarilgan does not exist:
$ go run uyga/oson/main.go
# command-line-arguments
uyga/oson/main.go:21:70: undefined: QaytarilganWhen you add the status correctly, it should print true false false.
🟡 Medium (uyga/orta/main.go): store the name, not the number, in the database. Write
HolatNomi(h Holat) string and HolatNomdan(s string) (Holat, error); an unknown name should return an error.
// 🟡 Vazifa: bazaga yoki JSON'ga raqam emas, nom saqlang ("paid"), shunda roʻyxat tartibi muhim boʻlmaydi.
// 1) HolatNomi(h Holat) string — Holat → "unknown" / "new" / "paid" / "cancelled"
// 2) HolatNomdan(s string) (Holat, error) — teskarisi; nomaʼlum nom uchun error qaytarsin (GO-X.03).
// Tekshirish: go run uyga/orta/main.go
// Kutilgan natija:
//
// paid 2 <nil>
// 0 nomaʼlum holat: "refund"
package main
import (
"errors"
"fmt"
)
type Holat int
const (
Nomalum Holat = iota
Yangi
Tolangan
Bekor
)
func HolatNomi(h Holat) string {
// VAZIFA
return ""
}
func HolatNomdan(s string) (Holat, error) {
// VAZIFA
return Nomalum, errors.New("hali yozilmagan")
}
func main() {
h, err := HolatNomdan(HolatNomi(Tolangan))
fmt.Println(HolatNomi(h), h, err)
h, err = HolatNomdan("refund")
fmt.Println(h, err)
}Right now the functions are empty (HolatNomi returns an empty string, so the first line starts with a space):
$ go run uyga/orta/main.go
0 hali yozilmagan
0 hali yozilmaganExpected output: paid 2 <nil> and 0 nomaʼlum holat: "refund" (“nomaʼlum holat” = “unknown status”).
Harder tasks are left from the first version of the lesson (homework/ ):
- 🟢 Easy: write constants for the days of the week with
iota. - 🟡 Medium: write a few bit flags with
iotaand combine them with bitwise OR (|). - 🟠 Hard: why does
1.5 * time.Secondnot compile, while1500 * time.Millisecondworks? - 🔴 Guru: find where the
timepackage usesiota, and explain whyMonthstarts at 1.
Answers: the uyga/javob/ folder and homework/README.md . Try it yourself first.
Answer
🟢 Qaytarilgan goes to the end of the list (= 4), and the old numbers stay where they are. A number written by
hand also works: Qaytarilgan Holat = 4.
// 🟢 Javob: yangi holat faqat roʻyxat oxiriga qoʻshiladi, shunda eski raqamlar joyida qoladi.
// (Qoʻlda yozilgan raqamlar bilan ham boʻladi: Qaytarilgan Holat = 4.)
package main
import "fmt"
type Holat int
const (
Nomalum Holat = iota // 0
Yangi // 1
Tolangan // 2: kechagi raqam joyida
Bekor // 3
Qaytarilgan // 4: yangi holat → oxiriga
)
func main() {
var saqlangan Holat = 2
fmt.Println(saqlangan == Tolangan, saqlangan == Bekor, saqlangan == Qaytarilgan)
}$ go run uyga/javob/oson/main.go
true false false🟡 HolatNomi gives each status a name; HolatNomdan goes through all statuses and returns the one whose name
matches:
// 🟡 Javob: nom ↔ Holat. Bazada "paid" saqlansa, const blokidagi tartib oʻzgarsa ham maʼno buzilmaydi.
package main
import "fmt"
type Holat int
const (
Nomalum Holat = iota
Yangi
Tolangan
Bekor
)
func HolatNomi(h Holat) string {
if h == Yangi {
return "new"
}
if h == Tolangan {
return "paid"
}
if h == Bekor {
return "cancelled"
}
return "unknown"
}
func HolatNomdan(s string) (Holat, error) {
for _, h := range []Holat{Nomalum, Yangi, Tolangan, Bekor} {
if HolatNomi(h) == s {
return h, nil
}
}
return Nomalum, fmt.Errorf("nomaʼlum holat: %q", s)
}
func main() {
h, err := HolatNomdan(HolatNomi(Tolangan))
fmt.Println(HolatNomi(h), h, err)
h, err = HolatNomdan("refund")
fmt.Println(h, err)
}$ go run uyga/javob/orta/main.go
paid 2 <nil>
0 nomaʼlum holat: "refund"for _, h := range []Holat{…} is a loop over each status in the list (like for (const h of [...]) in JS; range
in detail in later lessons). fmt.Errorf makes an error with a text, and %q writes the value in quotes. If the
database stores "paid", the meaning does not break even when the order in the const block changes.
The harder tasks (in detail in homework/README.md):
- 🟢 With
Monday Weekday = iota + 1, Monday starts at 1, and0stays “no day chosen”:homework/easy→1 5 7and0. The standardtime.Weekdayinstead hasSunday Weekday = iota, so Sunday is 0. - 🟡
Read Perm = 1 << iota→001,010,100: each flag is a separate bit, they combine with|and are checked with&.io/fs.FileModeis built the same way. - 🟠
1.5 * time.Second→1.5 (untyped float constant) truncated to int64: the untyped1.5does not convert exactly to aDuration, an integer, and a constant is never rounded. The right ways:1500 * time.Millisecondortime.Second * 3 / 2, both print1.5s. - 🔴
January Month = 1 + iota: months go from 1 to 12, the way people write them. Atime.Monthwith no value is 0, but there is no month 0:fmtprints it as%!Month(0). Here the Go team chose “the number equals the number people use”.
Sources
- Go’s official rules (Go spec): Constants , Constant expressions , Iota , Constant declarations , Type definitions , Address operators , The zero value
- Rob Pike, Constants (Go blog, 2014): https://go.dev/blog/constants · Go FAQ, implicit numeric conversions: https://go.dev/doc/faq#conversions
- The
timepackage:func Sleep,type Duration,time.go: Duration,Nanosecond … Second,time.Duration(seconds)*time.Second - MDN:
const,setTimeout - Python:
time.sleep, PEP 8, Constants - PHP: Constants, syntax
- TypeScript: Enums
- Protobuf: enum zero value , reserve deleted numbers
- staticcheck SA1004
- All results from
go1.26.8 linux/amd64, Node v24.10.0, Python 3.13.15, PHP 8.4.26 and tsc 5.9.3, on 2026-11-26.
Video and code
💻 Code and homework answers on GitHub
← Previous lesson: GO-1.02 · Next lesson: GO-1.04 → · All lessons
comments