Golang / GoLang Basics Interview Questions
How do constants and iota work in Go?
Constants are declared with const and must be assigned a value that is computable at compile time — no function calls or runtime values. The iota identifier provides an automatically incrementing integer within a const block, resetting to 0 at the start of each new block.
// Simple constants const Pi = 3.14159 const AppName = "MyService" // iota: auto-incrementing integer, resets at each const block type Weekday int const ( Sunday Weekday = iota // 0 Monday // 1 Tuesday // 2 Wednesday // 3 Thursday // 4 Friday // 5 Saturday // 6 ) // iota with bit-shifting â perfect for flag constants type Permission uint const ( Read Permission = 1 << iota // 1 (001) Write // 2 (010) Execute // 4 (100) ) userPerms := Read | Write // 3 â can read and write // iota with expressions const ( _ = iota // skip 0 KB = 1 << (10 * iota) // 1 << 10 = 1024 MB // 1 << 20 GB // 1 << 30 )
More Related questions...