Go Constants

Let’s learn the basic concepts of Go constants.

Introducing Go constants

Go supports constants, which are variables that cannot change their values. Constants in Go are defined with the help of the const keyword. Generally speaking, constants can be either global or local variables.

However, we might need to rethink our approach if we find ourselves defining too many constant variables with a local scope. The main benefit we get from using constants in our programs is the guarantee that their value will not change during program execution. Strictly speaking, the value of a constant variable is defined at compile-time, not at runtime—this means that it is included in the binary executable. Behind the scenes, Go uses boolean, string, or number as the type for storing constant values because this gives Go more flexibility when dealing with constants.

The next subsection discusses the constant generator iota, which is a handy way of creating sequences of constants.

The constant generator iota

The constant generator iota is used for declaring a sequence of related values that use incrementing numbers without the need to explicitly type each one of them.

Coding example

The concepts related to the const keyword, including the constant generator iota, are illustrated in the constants.go file.

Get hands-on with 1200+ tech skills courses.