Chapter 10: Go Constants
1. What is a Constant in Go? (Core Idea)
- A constant is a name bound to a compile-time fixed value.
- Value must be known at compile time (literals, expressions of constants only).
- Cannot be changed after declaration (no reassignment — compile error if you try).
- Unlike variables: constants can be untyped (very flexible) and have arbitrary precision (no overflow during computation).
- Types: boolean, rune, integer, floating-point, complex, string.
From the spec (go.dev/ref/spec#Constants — as of Go 1.26):
“There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.”
2. Declaration Styles (Similar to Variables — But No :=)
Three main ways — no short := for constants!
| Style | Syntax Example | Where Allowed | Type Required? | Common Use |
|---|---|---|---|---|
| Single const | const Pi = 3.14159 | Anywhere | Optional (inferred) | Simple values |
| Typed single | const MaxRetries int = 5 | Anywhere | Yes | Force type |
| Grouped const block | const ( … ) | Anywhere | Optional | Related constants / enums |
| With iota | const ( Sunday = iota … ) | Inside block | Usually inferred | Enum-like sequences |
Important: Value must be assigned at declaration — no “declare now, set later”.
3. Basic Examples (Run These!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package main import "fmt" const Pi = 3.14159265358979323846 // untyped float constant — arbitrary precision! const Greeting = "Hello from Hyderabad! 🇮🇳" // string constant const IsFun bool = true // typed boolean func main() { fmt.Println("Pi:", Pi) fmt.Println(Greeting) // Pi = 3.0 // ERROR: cannot assign to Pi (constant) // Math with constants — no overflow worry const huge = 1 << 100 // untyped int, exact value kept fmt.Println("2^100 =", huge) } |
Output (huge number prints exactly):
|
0 1 2 3 4 5 6 7 8 |
Pi: 3.141592653589793 Hello from Hyderabad! 🇮🇳 2^100 = 1267650600228229401496703205376 |
4. Typed vs Untyped Constants (The Magic Part)
- Untyped constants (most common & powerful): no fixed type → compiler chooses best type when used.
- Typed constants: forced to specific type (int32, float32, etc.).
Why untyped is awesome:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const MaxUint64 uint64 = 1<<64 - 1 // typed → must fit uint64 const HugeNumber = 1 << 1000 // untyped → can be used as int, float, etc. if fits func main() { var i int = HugeNumber // ok if int is 64-bit and value fits (compile error if not) var f float64 = HugeNumber // ok — converts to float // var u uint8 = HugeNumber // compile error — too big for uint8 } |
From Rob Pike’s blog (go.dev/blog/constants — still relevant 2026):
“In Go, constants behave pretty much like regular numbers… Constants can be huge, with arbitrary precision.”
5. Grouped Constants + iota (Enum-like — Very Common)
iota resets to 0 in each const block, increments by 1 each line.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
const ( Sunday = iota // 0 Monday // 1 Tuesday // 2 Wednesday // 3 Thursday // 4 Friday // 5 Saturday // 6 ) const ( // More realistic example — error codes ErrNone = iota ErrNotFound // 1 ErrInvalidInput // 2 ErrTimeout // 3 ) const ( // Bit flags (common pattern) FlagRead uint8 = 1 << iota // 1 (iota=0) FlagWrite // 2 (1<<1) FlagExecute // 4 (1<<2) FlagDelete // 8 (1<<3) ) |
Real code snippet (like time.Weekday in stdlib):
|
0 1 2 3 4 5 6 |
fmt.Println("Today is weekday:", Monday) // prints 1 |
6. Naming Conventions for Constants (2026 Style)
From Effective Go + stdlib:
- Use MixedCaps / camelCase — NO ALL_CAPS or underscores (unlike C/Java)
- Exported (public) → Uppercase first letter: MaxRetries, StatusOK
- Unexported (package-private) → lowercase: defaultTimeout, internalKey
- Short & descriptive — especially for local-ish use
- Stdlib examples: http.StatusOK, os.O_RDONLY, math.Pi, time.Monday
Bad (non-idiomatic):
|
0 1 2 3 4 5 6 7 |
const MAX_USERS = 100 // ALL_CAPS + underscore — avoid! const MAX_USERS_COUNT int = 100 |
Good:
|
0 1 2 3 4 5 6 7 |
const MaxUsers = 100 const DefaultPort = 8080 |
7. Common Use Cases & Patterns
- Mathematical constants: math.Pi, math.E
- HTTP / status codes: http.StatusNotFound
- Configuration defaults: const DefaultTimeout = 30 * time.Second
- Enums / states: iota for days, log levels, error codes
- Bitmasks: flags for permissions, options
8. Quick Exercise (Try in Playground or VS Code)
Fix & improve this:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
const max_retry = 5 const PI = 3.14 const ( RED = 1 GREEN = 2 BLUE = 3 ) |
Better version:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const MaxRetries = 5 const Pi = 3.141592653589793 const ( ColorRed = iota + 1 // 1,2,3... ColorGreen ColorBlue ) |
Any part confusing yet?
- Untyped vs typed deeper?
- iota skipping values / custom increments?
- Constants in expressions / build tags?
- Or ready for functions, pointers, structs next?
You’re doing fantastic — constants are where Go starts showing its numeric elegance! 💪 Keep coding, paste any experiment results or questions. 🇮🇳🚀
