What are Constants?
In Go, a constant is a value that cannot be changed once it's defined. Unlike variables, constants are determined at compile time, which means they are immutable and have several unique properties that set them apart from regular variables.
Basic Constant Declaration
Here's the simplest way to declare a constant in Go:
const pi = 3.14159
const greeting = "Hello, World!"
Types of Constants
Go supports several types of constants:
1. Typed Constants
When you specify a type explicitly, you create a typed constant:
const age int = 30
const temperature float64 = 98.6
2. Untyped Constants
Go also supports untyped constants, which are more flexible:
const x = 42 // untyped integer constant
const message = "Go" // untyped string constant
Untyped constants can be used more freely and are converted to the appropriate type when used.
Constant Declarations
Go provides multiple ways to declare constants:
Single Constant Declaration
const maxConnections = 100
Multiple Constant Declarations
const (
statusOK = 200
statusNotFound = 404
statusServerError = 500
)
Constant Expressions
Constants can be created using expressions that are evaluated at compile-time:
const (
secondsPerMinute = 60
minutesPerHour = 60
secondsPerHour = secondsPerMinute * minutesPerHour
)
Iota: The Constant Generator
iota
is a special identifier in Go used for creating incrementing constants:
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)
Common Pitfalls to Avoid
Don't use constants for values that might change at runtime.
Be cautious when using
iota
in complex scenarios.Remember that constants are compile-time constructs.