Skip to main content
eLearner.app
Module 1 · Lesson 3 of 53/50 in the course~10 min
Module lessons (3/5)

Constants and iota

Constants are immutable values known at compile time. In Go they are declared with const and can be typed or untyped. Untyped ones have a superpower: they adapt to the type required by the context, sparing you from having to write explicit conversions.

Basic syntax

Go
const PI = 3.14
const MaxRetry int = 5
const Name = "eLearner"

MaxRetry is typed (int): you can assign it only to an int. PI and Name are untyped: they behave like "literals" and adapt to the context.

Go
const PI = 3.14

var f float32 = PI  // ok: PI è non tipata, diventa float32
var d float64 = PI  // ok

const blocks

You can group several constants in a block:

Go
const (
    StateInitial = "INIT"
    StateReady   = "READY"
    StateError   = "ERROR"
)

iota: the enumeration counter

Inside a const block, the special identifier iota starts at 0 and increments by 1 on each line. It is the idiom for making enumerations:

Go
const (
    Monday = iota // 0
    Tuesday       // 1
    Wednesday     // 2
    Thursday      // 3
    Friday        // 4
)

Subsequent lines inherit the expression if they don't provide one. That's why writing Tuesday is enough without repeating = iota.

Patterns with expressions

iota can appear inside arbitrary expressions:

Go
const (
    KB = 1 << (10 * (iota + 1)) // 1 << 10 = 1024
    MB                          // 1 << 20
    GB                          // 1 << 30
    TB                          // 1 << 40
)

Skipping a value

If you don't want to assign a value to a line (because you want iota to increment anyway), use the blank identifier _:

Go
const (
    _  = iota // scarta 0
    KB        // 1
    MB        // 2
)

Your turn

Exercise#go.m1.l3.e1
Attempts: 0Loading…

Declare a constant PI with value 3.14 at package level, then print it inside main.

Loading editor…
Show hint

`const PI = 3.14` goes at package level, outside main.

Solution available after 3 attempts

Exercise#go.m1.l3.e2
Attempts: 0Loading…

Define a const block with the days of the week (Monday, Tuesday, Wednesday) numbered from 1 using iota.

Loading editor…
Show hint

Use `iota + 1` on the first line of the block; subsequent lines inherit the expression.

Solution available after 3 attempts

Quiz#go.m1.l3.e3
Ready

What does this program print?

Go
const (
    A = iota * 2
    B
    C
)
fmt.Println(A, B, C)
Answer options

Recap

  • const for immutable values known at compile time.
  • Untyped constants adapt to the context: no conversion needed.
  • const ( ... ) blocks group related values.
  • iota starts at 0 in every block and increments line by line.
  • Patterns: enum (= iota), bitmask (= 1 << iota), units (= 1 << (10*iota)).