Go Constants

Constants hold values that never change after they are declared, using Go's const keyword.

Declaring Constants

The const keyword declares a value that is fixed at compile time and can never be reassigned. Attempting to change a constant after it is declared results in a compile error.

Basic Constant

package main

import "fmt"

const Pi = 3.14159

func main() {
    fmt.Println("Pi is approximately", Pi)
}

Typed vs. Untyped Constants

A constant can be given an explicit type, like const Pi float64 = 3.14159, or left untyped, like const Pi = 3.14159. Untyped constants are flexible and adapt to whatever type they are used with, which makes them convenient for numeric literals.

Typed Constant

package main

import "fmt"

const MaxUsers int = 100

func main() {
    fmt.Println("The system allows up to", MaxUsers, "users")
}

Grouping Constants and iota

Related constants can be grouped in a single const block. Inside such a block, the special identifier iota starts at 0 and increases by one for each line, which is a common way to build simple enumerations.

Constants with iota

package main

import "fmt"

const (
    Sunday = iota // 0
    Monday        // 1
    Tuesday       // 2
    Wednesday     // 3
)

func main() {
    fmt.Println(Sunday, Monday, Tuesday, Wednesday)
}
  • Constants must be assignable at compile time, not from a function call result
  • Constants can be numbers, strings, characters, or booleans
  • Constants cannot be declared using the := operator
  • By convention, exported constants start with an uppercase letter
Aspectvarconst
Can change laterYesNo
Value known at compile timeNot requiredRequired
Declared with :=YesNo
Note: Use constants for values like mathematical constants, configuration limits, or fixed labels — anywhere a value should never accidentally change.
Note: const Total := 10 is invalid syntax — the short declaration operator := cannot be combined with the const keyword. Use const Total = 10 instead.

Exercise: Go Constants

Which keyword is used to declare a constant in Go?