Skip to content
AgileLogics
4 min read

Constants & iota

Prerequisites: Variables & data types

Syntax

const Pi = 3.14159
const Greeting string = "Hello"

const (
    MaxUsers = 100
    AppName  = "Tools"
)

A constant's value is fixed at compile time and can never change. Constants can only hold numbers, strings, and booleans.

Inside a const ( ... ) block, iota is a counter that starts at 0 and increases by one on each line. If a line omits its expression, it repeats the previous one — so iota makes numbered sequences (enumerations) easy:

Example

package main

import "fmt"

const (
    Small = iota // 0
    Medium       // 1
    Large        // 2
)

const (
    _      = iota // skip 0 with the blank identifier
    Bronze        // 1
    Silver        // 2
    Gold          // 3
)

func main() {
    fmt.Println(Small, Medium, Large)
    fmt.Println(Bronze, Silver, Gold)

    const hoursPerDay = 24
    fmt.Println(hoursPerDay * 7)
}

Expected output

0 1 2
1 2 3
168

Constants without an explicit type (like hoursPerDay above) are untyped: they adapt to whatever numeric type they're used with, so const Half = 0.5 works with any float type.

Common mistakes

  • Trying to assign to a constant later (Pi = 3) — a compile error.
  • Using a function call as a constant's value (const now = time.Now()) — constants must be known at compile time; use var instead.
  • Expecting iota to continue between separate const blocks — it resets to 0 in every block.

Practice

Use iota to define Red, Green, and Blue with the values 1, 2, and 3, and print them.

Show solution
package main

import "fmt"

const (
    Red = iota + 1
    Green
    Blue
)

func main() {
    fmt.Println(Red, Green, Blue) // 1 2 3
}