Last modified: Jan 23, 2026 By Alexander Williams
Go Constants vs Variables: When and How to Use
Choosing between constants and variables is a key decision in Go. It affects code safety and clarity. This guide explains when to use constants over variables.
Constants represent fixed values that cannot change. Variables hold values that can change during program execution. Using constants correctly makes your intent clear.
What Are Constants in Go?
Constants are immutable values. You declare them with the const keyword. Their value must be known at compile time.
This means you cannot set a constant to a value calculated at runtime. Constants provide safety. They prevent accidental changes to important values.
package main
import "fmt"
func main() {
// Declaring constants
const pi = 3.14159
const appName = "MyGoApp"
const maxRetries = 3
// This will cause a compile-time error
// const dynamicValue = getRuntimeValue() // Invalid
fmt.Println("Pi:", pi)
fmt.Println("App:", appName)
fmt.Println("Retries:", maxRetries)
}
Benefits of Using Constants Over Variables
Constants offer several advantages. They make your code more robust and easier to understand.
Prevent Accidental Modification
This is the primary benefit. Once a constant is set, it cannot be reassigned. This eliminates a whole class of bugs.
Compiler Optimizations
The Go compiler can perform optimizations with constants. It can inline their values directly. This can lead to slightly faster code.
Clearer Code Intent
Using a constant signals to other developers that a value is fixed. It is part of the contract of your code. This improves readability and maintainability.
For managing values that do change, understanding Go Best Practices for Temporary Variables is crucial.
When to Use Constants Instead of Variables
Use constants for values that have a logical, unchanging meaning in your program's context.
Configuration and Settings
Use constants for fixed configuration values. This includes timeouts, limits, and application names.
package main
import "fmt"
func main() {
// Good use of constants for configuration
const (
requestTimeout = 30 // seconds
maxFileSize = 10 * 1024 * 1024 // 10 MB
defaultPort = "8080"
)
fmt.Printf("Timeout: %ds, Max Size: %d bytes, Port: %s\n",
requestTimeout, maxFileSize, defaultPort)
}
Mathematical and Physical Constants
Values like Pi, gravitational acceleration, or conversion factors are perfect for constants.
Status Codes and Enumerations
HTTP status codes, error codes, or state identifiers should be constants. The iota keyword is great for this.
package main
import "fmt"
func main() {
// Using iota for enumerated constants
const (
StatusPending = iota // 0
StatusProcessing // 1
StatusSuccess // 2
StatusFailed // 3
)
currentStatus := StatusProcessing
fmt.Println("Current Status Code:", currentStatus)
}
String Literals Used Repeatedly
If you use the same string in multiple places, make it a constant. This prevents typos and makes updates easy.
Typed vs. Untyped Constants
Go has a powerful concept of untyped constants. An untyped constant has a kind (like string or number) but no fixed type.
It gains a type when used in a context that requires one. This allows for flexibility. Typed constants behave like variables of that type.
package main
import "fmt"
func main() {
// Untyped constant
const untypedValue = 100
// Typed constant
const typedValue int = 100
var f float64
f = untypedValue // Works: untypedValue becomes float64
// f = typedValue // Error: cannot use typedValue (type int) as float64
fmt.Println("Float from untyped constant:", f)
}
Understanding types is key. Learn more about verifying them in our guide on how to Check Variable Type at Runtime in Go.
Common Constant Patterns and Examples
Constants are often grouped. They can be used in calculations. They work well with other language features.
Grouping Related Constants
Use a parenthesized const block. This groups related constants together logically.
package main
import "fmt"
func main() {
const (
daysInWeek = 7
hoursInDay = 24
minutesInHour = 60
secondsInMinute = 60
)
secondsInWeek := daysInWeek * hoursInDay * minutesInHour * secondsInMinute
fmt.Println("Seconds in a week:", secondsInWeek)
}
Constants in Functions and Calculations
Constants can be used anywhere a literal value can. This includes function arguments and mathematical expressions.
package main
import "fmt"
const taxRate = 0.08 // 8%
func calculateTotal(price float64) float64 {
return price + (price * taxRate)
}
func main() {
subtotal := 50.0
total := calculateTotal(subtotal)
fmt.Printf("Subtotal: $%.2f, Total with tax: $%.2f\n", subtotal, total)
}
For more on handling values that change, see Go Type Conversion: Safe Variable Changes.
Conclusion
Using constants effectively is a mark of clean Go code. They protect values from change. They communicate intent clearly. They allow for compiler optimizations.
Prefer constants for magic numbers, configuration, and fixed business logic. Use variables for data that changes state. This simple rule improves code quality.
Start reviewing your code. Replace suitable variables with constants. Your future self and teammates will thank you. Your programs will be more predictable and easier to debug.