ProgramGuru

Constants

Start with Go Constants

A constant is a named value that cannot be reassigned after it is declared. Constants are useful for fixed settings, labels and values that should never change at runtime.

What you’ll learn

  • Declare and use named constants.
  • Understand a practical use for iota.
  • Distinguish compile-time constants from mutable variables.

Understand the idea

Declare constants with const. Numeric constants can be untyped, meaning Go keeps them flexible until they are used in a typed context. Constants can represent numbers, strings, booleans and certain constant expressions; they cannot hold arbitrary runtime results.

The iota identifier helps define related integer constants by generating successive values within a constant declaration group. A regular variable remains appropriate when the value may change.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

const taxRate = 5
const (
	Pending = iota
	Approved
	Rejected
)

func main() {
	price := 100
	fmt.Println("Tax:", price*taxRate/100)
	fmt.Println("Statuses:", Pending, Approved, Rejected)
}

Output

Tax: 5
Statuses: 0 1 2

Trace what the program does

The tax calculation uses the constant taxRate without changing it. In the grouped declaration, iota is 0 for Pending, 1 for Approved and 2 for Rejected. The output is deterministic.

Avoid common mistakes

  • A constant cannot be assigned with = after declaration.
  • iota has meaning in constant declarations, not as an ordinary mutable counter.

Try it yourself

Create a constant for the number of months in a year, use it in a calculation, and verify you cannot reassign it.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What makes a constant different from an ordinary variable?
Choose one answer. You can try again.

Answer and explanation

A constant cannot be changed by assignment at runtime

Correct. The tax calculation uses the constant taxRate without changing it.

What you should remember

You have practiced Go Constants in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Data Types →