const declares compile-time constants. Go constants can be untyped numeric literals that adapt to context—unlike Java final fields that are still typed variables.
Basic constants
const Pi = 3.14159
const Greeting = "hello"
Constants cannot be reassigned. They may use expressions of other constants as long as values are computable at compile time.
iota enumerations
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
)
iota resets to 0 in each const block and increments per line—idiomatic for enums and bitmasks.
Important interview questions and answers
- Q: What is iota?
A: A counter in const blocks starting at 0, incrementing each line—used for enumerations and flags. - Q: const vs var?
A:constvalues are fixed at compile time;varcan change at runtime.
Self-check
- What value does the second iota line get in a block?
- Can a const hold a slice?
Tip: Each const block resets iota to 0—start a new block when defining unrelated enumerations.
Interview prep
- What is iota?
A counter in const blocks starting at 0, incrementing per line—idiomatic for enumerations.
- Can const be a slice?
No—constants must be compile-time representable; slices are not constant.