Go Constants

Go Constants

Kishore V


Go Constants

In Go, constants are used to store values that must remain unchanged throughout the program. Unlike variables, constants are immutable—once assigned, their value cannot be modified.

Constants are declared using the const keyword, making your code safer and more predictable when working with fixed values such as mathematical constants, configuration settings, or limits.

Syntax of Constants in Go

const name type = value
  • name: Identifier of the constant
  • type: Optional (can be inferred)
  • value: Must be assigned at declaration

Important: A constant must always be initialized at the time of declaration.

Declaring a Constant

Here’s a simple example of defining and using a constant:

Maximum allowed users: 100

Key Rules for Constants

  • Follow the same naming rules as variables
  • Must be assigned a value at declaration
  • Cannot be reassigned after initialization
  • Can be declared inside or outside functions
  • Commonly written in uppercase for visibility (not mandatory, but recommended)

Typed vs Untyped Constants

Go supports two types of constants: typed and untyped. Understanding the difference helps you write more flexible and precise code.

Typed Constants

A typed constant has an explicitly defined data type. It behaves like a variable of that type but remains immutable.

Timeout: 30

When to use:

  • When you want strict type control
  • When interacting with APIs or functions requiring specific types

Untyped Constants

Untyped constants do not have a fixed type until they are used. Go determines the type based on context.

Final price: 170

Advantages:

  • More flexible in expressions
  • Automatically adapts to the required type

Advanced Example: Constant Grouping

You can group multiple constants together for better organization:

ShopEasy Version: 1.0.0 Max retries: 3


Our website uses cookies to enhance your experience. Learn More
Accept !