Go by Example: Constants
Explore how to declare and use constants in Go. This sample demonstrates defining immutable values that are evaluated at compile time, including typed and untyped constants, and explains their role in creating safer and more efficient code.
Code
package main
import "fmt"
const Pi = 3.14
const Greeting = "Hello"
func main() {
const LocalConst = 42
fmt.Println(Pi, Greeting, LocalConst)
const (
StatusOK = 200
StatusNotFound = 404
)
fmt.Println(StatusOK, StatusNotFound)
}Explanation
Constants in Go are declared using the const keyword and represent fixed, immutable, read-only values that are evaluated and resolved entirely at compile time. Unlike variables, constants are not runtime objects—the compiler directly substitutes their actual values into the machine code wherever they're referenced. This compile-time substitution means constants don't occupy memory during program execution and enable the compiler to perform optimization techniques like constant folding.
Constants must be assigned values that can be determined at compile time, which means you cannot use function calls or any value requiring runtime computation. Only basic types are allowed: booleans, numbers (integers, floats, complex numbers), and strings. Constants can be declared individually or grouped in a const block for better organization of related values.
Go supports both typed and untyped constants. Untyped constants possess a "kind" (integer, floating-point, boolean, or string) but offer remarkable flexibility through implicit conversions. The compiler can convert an untyped constant to any compatible type if the value is representable, providing convenience without sacrificing type safety. Typed constants, declared with explicit types, enforce stricter type checking.
The iota identifier is a powerful tool used within const declarations to create incrementing constants, particularly useful for creating enumerations. iota starts at 0 and automatically increments by one for each subsequent constant in a const block, resetting to 0 when a new block is encountered.
Key advantages of constants:
- Compile-time evaluation eliminates runtime overhead
- Immutability guarantees values cannot be accidentally modified
- Type safety with explicit or inferred types
- Enhanced code readability with named values instead of magic numbers
- Compiler optimizations through constant expression folding

