Constants in Golang (Because Some Things Should Never Change!)

 

Go (or Golang, if you like sounding fancy) has a special category of variables that never change—constants. Unlike regular variables that can be reassigned, constants are set in stone. Once you declare them, they stay the same forever, just like your undying love for Go (hopefully).

What Are Constants?

A constant is a fixed value that cannot be modified during the execution of a program. It’s like a stubborn grandparent who refuses to change their opinion—no matter what you do, it stays the same!

Declaring Constants in Go

Declaring a constant in Go is as easy as pie:

const Pi = 3.1415

Now, Pi will always be 3.1415—you can’t suddenly decide it should be 42 (sorry, math rebels!).

Multiple Constants Declaration

Got multiple constants? You can declare them in a block to keep things tidy:

const (
    EarthGravity = 9.81
    SpeedOfLight = 299792458
    GoldenRatio  = 1.618
)

Typed vs Untyped Constants

In Go, constants can be typed or untyped:

const TypedPi float64 = 3.1415  // Typed constant
const UntypedPi = 3.1415        // Untyped constant

An untyped constant can adapt its type depending on where it's used, while a typed constant is locked into a specific type. Kind of like how some people adapt to different social groups while others are just... set in their ways.

Why Use Constants?

  • Prevents accidental modification: No more “Oops! I changed a crucial value!”
  • Improves readability: const Pi = 3.14 is way clearer than 3.14 appearing randomly in your code.
  • Boosts performance: Constants are resolved at compile-time, making them faster than variables.

Constant Expressions

Go allows constants to be the result of expressions:

const HoursPerDay = 24
const MinutesPerDay = HoursPerDay * 60

This makes calculations easy and prevents errors caused by repeated manual values.

Constants in Go ensure stability in your programs. They’re reliable, predictable, and won’t change on you—unlike that one flaky friend. Now, go forth and declare some constants! Because some things should never change. 

Post a Comment

0 Comments