Go Constants

Understanding immutable values in Go programming

🔒 What are Go Constants?

Constants are fixed values that cannot be changed during program execution. They store unchanging data like mathematical values, configuration settings, or fixed text throughout your application.


// Constants cannot be changed
const pi float64 = 3.14159
const appName string = "MyApp"
const maxUsers int = 1000
fmt.Println(pi, appName, maxUsers)
                                    

Output:

3.14159 MyApp 1000

Key Constants Concepts

🔐

Immutable

Values cannot be changed after declaration

const name = "Alice"

Compile Time

Values must be known at compile time

const size = 100
🎯

Typed/Untyped

Can have explicit or inferred types

const pi = 3.14
📦

Block Declaration

Group constants together

const (
    x = 1
    y = 2
)

🔹 Basic Constant Declaration

Simple ways to declare constants:

// Basic constant declarations
const companyName string = "TechCorp"
const foundedYear int = 2010
const pi float64 = 3.14159
const isActive bool = true

// Constants with type inference
const version = "1.0.0"
const maxConnections = 100
const rate = 0.05

fmt.Printf("Company: %s (Founded: %d)\n", companyName, foundedYear)
fmt.Printf("Version: %s, Max Connections: %d\n", version, maxConnections)
fmt.Printf("Pi: %.3f, Rate: %.2f, Active: %t\n", pi, rate, isActive)

Output:

Company: TechCorp (Founded: 2010)

Version: 1.0.0, Max Connections: 100

Pi: 3.142, Rate: 0.05, Active: true

🔹 Multiple Constants Declaration

Declare multiple constants at once:

// Multiple constants in one line
const width, height int = 800, 600
const firstName, lastName = "John", "Doe"

// Block declaration for better organization
const (
    StatusActive   = "active"
    StatusInactive = "inactive"
    StatusPending  = "pending"
    
    MinAge = 18
    MaxAge = 65
    
    DefaultTimeout = 30
    MaxRetries     = 3
)

fmt.Printf("Screen: %dx%d\n", width, height)
fmt.Printf("User: %s %s\n", firstName, lastName)
fmt.Printf("Status: %s, Age Range: %d-%d\n", StatusActive, MinAge, MaxAge)
fmt.Printf("Timeout: %ds, Retries: %d\n", DefaultTimeout, MaxRetries)

Output:

Screen: 800x600

User: John Doe

Status: active, Age Range: 18-65

Timeout: 30s, Retries: 3

🔹 Constants vs Variables

Understanding the key differences:

// Constants - cannot be changed
const appVersion = "2.1.0"
const maxFileSize = 1024

// Variables - can be changed
var currentUser = "alice"
var fileCount = 5

fmt.Printf("App Version: %s (constant)\n", appVersion)
fmt.Printf("Max File Size: %d MB (constant)\n", maxFileSize)
fmt.Printf("Current User: %s (variable)\n", currentUser)
fmt.Printf("File Count: %d (variable)\n", fileCount)

// This works - changing variables
currentUser = "bob"
fileCount = 10

// This would cause an error - cannot change constants
// appVersion = "2.2.0"  // Error!
// maxFileSize = 2048    // Error!

fmt.Printf("Updated User: %s, Files: %d\n", currentUser, fileCount)

Output:

App Version: 2.1.0 (constant)

Max File Size: 1024 MB (constant)

Current User: alice (variable)

File Count: 5 (variable)

Updated User: bob, Files: 10

🔹 Practical Constants Example

Real-world usage of constants in applications:

// Application configuration constants
const (
    AppName        = "E-Commerce Store"
    AppVersion     = "1.2.3"
    DatabaseURL    = "localhost:5432"
    
    // HTTP Status codes
    StatusOK       = 200
    StatusNotFound = 404
    StatusError    = 500
    
    // Business rules
    FreeShippingLimit = 50.0
    TaxRate          = 0.08
    MaxItemsInCart   = 20
)

// Using constants in calculations
var orderTotal float64 = 75.50
var itemCount int = 3

fmt.Printf("=== %s v%s ===\n", AppName, AppVersion)
fmt.Printf("Order Total: $%.2f\n", orderTotal)

if orderTotal >= FreeShippingLimit {
    fmt.Println("✓ Free shipping applies!")
} else {
    fmt.Printf("Add $%.2f more for free shipping\n", FreeShippingLimit-orderTotal)
}

tax := orderTotal * TaxRate
finalTotal := orderTotal + tax

fmt.Printf("Tax (%.1f%%): $%.2f\n", TaxRate*100, tax)
fmt.Printf("Final Total: $%.2f\n", finalTotal)
fmt.Printf("Items in cart: %d/%d\n", itemCount, MaxItemsInCart)

Output:

=== E-Commerce Store v1.2.3 ===

Order Total: $75.50

✓ Free shipping applies!

Tax (8.0%): $6.04

Final Total: $81.54

Items in cart: 3/20

🧠 Test Your Knowledge

What happens if you try to change a constant value in Go?