Skip to main content
A constant in Go is an immutable, compile-time construct representing a fixed value. Declared using the const keyword, constants are evaluated by the compiler rather than at runtime. They are strictly limited to boolean, rune, integer, floating-point, complex, and string types.

Syntax

Constants can be declared individually or grouped within a block.

Typed vs. Untyped Constants

Go distinguishes between typed and untyped constants, a mechanism that provides flexibility within its strict type system. Untyped Constants An untyped constant possesses a value and a default type (e.g., int for 42, float64 for 3.14), but it is not strictly bound to that type. Numeric untyped constants exist in an arbitrary-precision mathematical space. They do not overflow and can be implicitly converted to any compatible type upon assignment.
Typed Constants A typed constant is explicitly bound to a specific Go type. Once typed, the constant loses its arbitrary precision and is subject to the memory bounds and overflow rules of its underlying type.

Constant Expressions

Expressions consisting entirely of constants are evaluated at compile time. The result of a constant expression is itself a constant. If the operands are untyped, the result remains untyped, maintaining arbitrary precision during intermediate calculations.

The iota Identifier

iota is a predeclared identifier used exclusively within const declarations to generate sequences of numbers. It represents successive untyped integer constants. iota is reset to 0 whenever the reserved word const appears in the source code and increments by 1 after each ConstSpec (constant specification) within a block.
iota can be combined with constant expressions to generate complex compile-time sequences, such as bitwise shifts.

Implicit Repetition

In a grouped constant declaration, if the expression list is omitted, the compiler implicitly repeats the preceding expression and its type.
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More