ProgrammingGo Developer

Explain the features of working with constants (const), iota, and types in Go. Why can the assignment of iota constants with an implicit type yield unexpected results?

Pass interviews with Hintsage AI assistant

Answer

Constants (const) in Go are evaluated at compile time and can have an implicit type. iota is a special identifier used to generate successive values when declaring constant blocks. iota increments by one within the block for each new constant.

Assignment without specifying a type leads to the constant possibly obtaining a type different from what the developer expects, especially if it is involved in arithmetic or logical operations. This risks implicit conversions and compile-time errors.

Example:

type Level int const ( Low Level = iota // Low: Level == 0 Medium // Medium: Level == 1 High // High: Level == 2 ) // And if the type is not specified: const ( Foo = iota // Foo: int == 0 Bar // Bar: int == 1 )

Trick Question

Can the value of a constant using iota be "typed" and what type will it be if the type is not explicitly specified?

Answer: If the type is not explicitly specified, the constant becomes untyped and receives a type inferred from its context of use (for example, int if used in arithmetic). This can lead to problems when using type aliases or when strict typing is required.

Example:

type Status uint8 const ( Ready Status = iota+1 // Ok // if it were simply declared as const Ready = iota+1 — the type would be int, not Status )

Examples of real errors due to not knowing the subtleties of the topic


Story

When serializing the status via json, the developer declared a const with iota without an explicit type. The result — the serialization outputs int instead of a human-readable string, causing the frontend to incorrectly interpret the received value.


Story

In the project, a type State (type State int) was introduced, but the constants remained declared without a type. This led to interfaces being unable to accept values of type State, causing unpleasant bugs related to type mismatches when comparing constants and variables.


Story

An engineer added a new enum value via iota without specifying a type. As a result, the compiler allowed comparisons of the constant with any other variable of type int, leading to errors in branching business logic in production.