What does this program print? (iota)
Question 3HardGo 1.22 to 1.25
type Size int64
const (
_ = iota // iota = 0, skipped
KB Size = 1 << (10 * iota) // iota = 1
MB // iota = 2: repeats the expression
GB // iota = 3
)
const (
A, B = iota, iota * 10 // 0, 0
C, D // 1, 10
E = "x" // iota is 2, but not used
F // repeats "x"
G = iota // 4
)
func main() {
fmt.Println(KB, MB, GB)
fmt.Println(A, B, C, D, E, F, G)
}
Output:
1024 1048576 1073741824
0 0 1 10 x x 4
Why:
iotais the index of the ConstSpec (the line) inside aconstblock. It starts at 0 and resets in every new block.- It goes up once per line, not once per identifier, so
AandBon the same line both see 0. - A line with no expression repeats the previous expression and its type, but uses the current
iota. That is whyFis"x"andMBis1<<20. - Lines that don't use
iotastill move it forward, soGis 4.
What the interviewer wants to hear: use _ = iota to skip zero, so that the zero value can mean "unknown" or "unset". Also know how to use a typed first constant (like Size above) to build type-safe enums.
More on Language Fundamentals & Types
- Q1What are the zero values of Go's types, and which zero values are "usable" versus dangerous?
- Q2What is the difference between
newandmake? - Q4What are untyped constants? Explain why
const huge = 1 << 100compiles. - Q5What is the difference between a typed and an untyped constant when you assign or compare it?
- Q6Explain variable shadowing. Find the bug in this code.
- Q7What are the rules for
:=redeclaration, and why does this not compile?