What values do the constants get from iota in these two const blocks?
Read the two const blocks below. The first uses a bare iota with a skipped _ line; the second uses a shift expression 1 << (10 * (iota + 1)).
Determine the value of every named constant: A, B, D, KB, MB.
const (
A = iota
B
_
D
)
const (
KB = 1 << (10 * (iota + 1))
MB
)
Predict the output.
A=0, B=1, D=3 — iota starts at 0 in each const block and increments by one per line, including the skipped _ line (which consumes value 2). In the second block KB = 1 << (10 * (iota + 1)) gives KB=1024 and MB=1048576, because iota is 0 then 1 on successive lines.
- ✗Thinking a skipped
_line does not advanceiota— it still consumes a value - ✗Believing
iotais a global counter rather than resetting perconstblock - ✗Forgetting
iotais evaluated inside the full line expression, e.g.1 << (10*(iota+1))
- →How would you define
KB, MB, GBas power-of-two sizes using oneiotaexpression? - →What happens to
iotaif two constants share a single line viaA, B = iota, iota?
What values do the constants have?
const (
A = iota // ?
B // ?
_ // skip
D // ?
)
const (
KB = 1 << (10 * (iota + 1)) // ?
MB // ?
)
Values
A=0 B=1 D=3
KB=1024 MB=1048576
How iota counts
iota is a per-line counter inside a const block. It resets to 0 at the start of each block and increases by one on every spec line, even when the line is a blank _ or repeats the previous expression.
First block:
A = iota→ line 0 →0B(repeats= iota) → line 1 →1_→ line 2 → value2discardedD→ line 3 →3
The second block restarts iota at 0. The expression 1 << (10 * (iota + 1)) is evaluated on each line:
KB→iota=0→1 << 10=1024MB→iota=1→1 << 20=1048576
⚠️ A skipped _ still consumes a number — forgetting this shifts every later value.