Go Constants

A constant holds a value that never changes once set. Where a variable can be updated at any point in the program, a constant is fixed for the entire lifetime of the program. Constants make code safer and more readable by naming important fixed values.

Declaring a Constant

Use the const keyword to declare a constant.

package main

import "fmt"

const Pi = 3.14159
const AppName = "eStudy247"
const MaxScore = 100

func main() {
    fmt.Println(Pi)       // 3.14159
    fmt.Println(AppName)  // eStudy247
    fmt.Println(MaxScore) // 100
}

Typed vs Untyped Constants

Typed Constant

A typed constant has an explicit type attached to it.

const Gravity float64 = 9.8

Untyped Constant

An untyped constant has no explicit type. Go assigns a type only when the constant is actually used in an expression.

const Limit = 50   // untyped — becomes int, float, etc. as needed

Multiple Constants Block

package main

import "fmt"

const (
    StatusOK      = 200
    StatusNotFound = 404
    StatusError    = 500
)

func main() {
    fmt.Println(StatusOK)       // 200
    fmt.Println(StatusNotFound) // 404
    fmt.Println(StatusError)    // 500
}

iota – Auto-Incrementing Constants

iota is a special keyword used inside a const block. It starts at 0 and increases by 1 for each new constant in the block. It is perfect for creating numbered lists like days, directions, or status codes.

package main

import "fmt"

const (
    Sunday    = iota // 0
    Monday           // 1
    Tuesday          // 2
    Wednesday        // 3
    Thursday         // 4
    Friday           // 5
    Saturday         // 6
)

func main() {
    fmt.Println(Monday)   // 1
    fmt.Println(Saturday) // 6
}

iota with Custom Values

const (
    Small  = iota * 10 // 0
    Medium             // 10
    Large              // 20
    XLarge             // 30
)

Constants vs Variables

FeatureConstantVariable
Value changes?NeverYes, anytime
Keywordconstvar or :=
Use caseFixed values like Pi, max limitsValues that update over time
Computed atCompile timeRuntime

Key Points

  • Constants are declared with const and cannot be changed after declaration
  • Untyped constants adapt their type based on how they are used
  • iota generates sequential numbers automatically inside a const block
  • Use constants for values like status codes, limits, and mathematical constants

Leave a Comment