Constants and iota in Go
Constants are values that do not change during program execution.
Go provides the const keyword to define constants and
iota to create enumerated values efficiently.
Constants make programs safer, clearer, and easier to maintain.
Why Use Constants?
Constants are used when a value should remain fixed throughout the program.
- Improve code readability
- Prevent accidental modification
- Make programs easier to update
- Represent fixed business rules
Examples include tax rates, limits, configuration flags, and status codes.
Declaring Constants
Constants are declared using the const keyword.
const pi = 3.14159
const appName = "Dataplexa"
const maxUsers = 1000
Once declared, a constant value cannot be changed.
Typed vs Untyped Constants
Go supports both typed and untyped constants.
Untyped Constants
The type is inferred when the constant is used.
const discount = 10
finalPrice := 100 - discount
Typed Constants
The type is explicitly defined.
const taxRate float64 = 7.5
Typed constants enforce stricter type rules.
Declaring Multiple Constants
Go allows grouping constants using parentheses.
const (
minAge = 18
maxAge = 60
country = "USA"
)
This improves organization and readability.
What Is iota?
iota is a special identifier in Go used to create sequential
constants automatically.
It starts from 0 and increments by 1 for each constant in a block.
Basic iota Example
const (
Sunday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
Values assigned:
- Sunday → 0
- Monday → 1
- Tuesday → 2
- ...
Using iota for Status Codes
A common real-world use case is defining application states.
const (
StatusPending = iota
StatusApproved
StatusRejected
)
This ensures consistent and readable status handling across the application.
Skipping Values with iota
You can skip values using the blank identifier.
const (
_ = iota
Low
Medium
High
)
Here, Low starts from 1 instead of 0.
iota with Expressions
You can combine iota with arithmetic operations.
const (
KB = 1 << (10 * iota)
MB
GB
TB
)
This is commonly used for memory sizes.
Real-World Example
In a subscription system:
const (
FreePlan = iota
BasicPlan
PremiumPlan
)
Using constants prevents errors caused by magic numbers.
Rules and Limitations
- Constants cannot use
:= - Constants cannot be assigned runtime values
- Constants are evaluated at compile time
Example of invalid constant:
// invalid
const timeNow = time.Now()
Practice Exercise
Task
Create constants for:
- Three user roles using
iota - A fixed tax percentage
- A maximum login limit
Print their values using fmt.Println().
What You Will Learn Next
In the next lesson, you will learn about operators in Go, which allow you to perform calculations, comparisons, and logical operations.