GO Tutorial



CONSTANTS IN GO


Constants in Go

Constants are fixed values that cannot be changed during program execution. They are useful for values that remain the same throughout your code.

Declaring Constants

Use the const keyword to declare a constant. You must assign a value when declaring it:

const Pi = 3.14159
const Greeting = "Hello, Go!"
const IsActive = true
  

Multiple Constants Declaration

You can declare multiple constants together in a block:

const (
    StatusOK       = 200
    StatusNotFound = 404
    StatusError    = 500
)
  

Typed vs Untyped Constants

Constants in Go can be typed or untyped. Untyped constants can be assigned to variables of different compatible types.

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

Interactive Example: Try to Change a Constant

Click the button below to see what happens if you try to change a constant value in Go:

Why Use Constants?

  • Improves code readability: Named constants clarify the meaning of values.
  • Avoids magic numbers: Prevents using unexplained literal values in code.
  • Safer code: Prevents accidental modification of important values.
Quick Tip: Use constants for fixed configuration values like URLs, error codes, and mathematical constants.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review