Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 147 ยท Variables and Types

Constants and iota

Learn Go constants - const, typed versus untyped constants, arbitrary-precision constant math, iota enums, bit flags and constant expressions.

A constant is a name for a value that never changes. Where a variable can be reassigned, a constant is fixed when your program is compiled. Constants are perfect for things like the number of days in a week, a maximum retry count, a mathematical value such as pi, or the set of states a document can be in.

Go's constants are more powerful than in most languages. Many of them are untyped and are calculated with arbitrary precision by the compiler, which makes them unusually flexible. Go also has iota, a small keyword that makes numbered lists of related constants (what other languages call enums) concise. This lesson covers all of it: const declarations, typed and untyped constants, constant expressions, iota patterns, and the limits of what can be a constant.

Declaring constants

Use the const keyword. Like variables, constants can be declared one at a time or grouped:

Go Declaring constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A constant must be given a value, and that value must be known at compile time. You can't write const now = time.Now(), because the time is only known when the program runs. Only booleans, numbers (including runes) and strings can be constants. You can't have a constant slice, map, struct or array.

Trying to change a constant is a compile error:

Go Assigning to a constant (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports:

TEXT
./main.go:8:2: cannot assign to limit (neither addressable nor a map index expression)

The build fails, so nothing runs.

Typed and untyped constants

Here is the idea that sets Go apart. A constant declared without a type is an untyped constant. It has a kind (integer, floating-point, rune, string or boolean) but no fixed type, so it adapts to wherever you use it:

Go An untyped constant adapts to its context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The same constant big becomes an int, an int64, a float64, a uint16 and even a complex128, with no conversion. If you declare the constant with a type, it behaves like a variable of that type and loses the flexibility:

Go
const typed int = 1000

var f float64 = typed // compile error: cannot use typed (constant of type int) as float64 value

So when do you add a type? When the constant belongs to a specific named type (usually an enum, shown below) or when you purposely want to prevent mixing it with other types. For ordinary numbers and strings, leave it untyped.

Default types

When there is no context to decide the type, such as x := 42, an untyped constant takes its default type: int for integer constants, float64 for floating-point, rune (that is, int32) for character constants like 'a', string and bool.

Go Default types of untyped constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The kinds are ordered integer, rune, floating-point, complex, so 1 + 2.5 is a floating-point constant and 'a' + 1 is still a rune constant.

Constants have arbitrary precision

The compiler evaluates untyped constant expressions with far more precision than any machine type offers (at least 256 bits for integers, according to the Go specification, and in practice much more). Nothing overflows until the final value has to be stored in a typed variable:

Go Constant arithmetic beyond 64 bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Untyped constants also explain code such as 1e6 * time.Second: 1e6 is an untyped floating-point constant, and because the value is exactly representable as an integer it converts to time.Duration (an int64 count of nanoseconds), giving 1,000,000 seconds. The same expression with a float variable would not compile.

huge is a perfectly good constant, even though no int could hold it. The calculations huge >> 98 and huge / (1 << 90) are done exactly at compile time, and only the small results are stored. If you uncomment the commented line, the compiler complains that the constant overflows int.

The last four lines show exact constant arithmetic in action. The compiler adds 0.1 + 0.2 exactly and gets precisely 0.3, so the first comparison prints true. With two float64 variables the same sum goes through binary floating point and comes out as 0.30000000000000004, so the second comparison prints false. Read numbers and math to learn why floating point behaves like this.

Compile-time arithmetic applies only to constant expressions. x * 2 where x is a variable is calculated when the program runs, in the type of x.

Constant expressions and what can be used

A constant expression is built from constants, operators, and a small set of built-in functions that are evaluated at compile time:

  • literals, other constants and iota;
  • arithmetic, comparison, logical, bit and shift operators on constants;
  • conversions between constant types, such as float64(3) or string("x") (but string(65) is a vet warning; see strings and runes);
  • len and cap of arrays and constant strings, unsafe.Sizeof(...), real, imag, complex, min and max.
Go Constant expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A function you wrote yourself can never appear in a constant expression, nor can most standard-library functions. That is why const x = math.Sqrt(2) doesn't compile, but const x = math.Pi * 2 does (math.Pi is itself a constant).

Enumerations with iota

Go has no enum keyword. Instead, inside a const group, the predeclared identifier iota counts up from 0 for each line (each ConstSpec). If you leave off the expression on a later line, Go repeats the previous one:

Go Your first iota enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Only the first line (Sunday Weekday = iota) spells out the type and expression; the other lines inherit both. Giving the enum its own defined type (Weekday) is idiomatic: it stops you passing any random int where a day is expected, and lets you attach methods such as String(). Defined types are covered shortly.

iota resets to 0 in every new const (...) group, and it increases by one for every line, whether or not the line uses it.

Starting at 1 and skipping values

Often 0 should mean "unset", so you start real values at 1. Use the blank identifier to skip a value, or add an offset:

Go Skipping and offsetting iota

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Making the zero value an explicit "invalid" or "unknown" state is a common safeguard: a forgotten field in a struct won't silently look like a real status.

Bit flags and sizes

Because iota works inside any constant expression, it is great for powers of two. This is how you declare permission flags that can be combined with |:

Go Bit flags with iota

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The operators |, & and << are explained in operators. The size example shows another trick: a typed iota expression with a shift, 1 << (10 * iota), gives 1024, then 1024 squared, and so on.

Several constants per line

Everything on one line shares the same iota, which lets you build small tables:

Go
const (
	a, b = iota, iota * 10 // 0, 0
	c, d                   // 1, 10
	e, f                   // 2, 20
)

When an enum is going to be printed or logged, give its type a String() method like Weekday above, or generate one with the stringer tool. Otherwise you'll see bare numbers in your logs. The method is picked up by fmt automatically, as the printing lesson previews.

A word about typed constants and overflow

A typed constant must fit its type, and the compiler checks it:

Go A constant that does not fit (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error is caught before the program ever runs:

TEXT
./main.go:9:17: cannot use big (untyped int constant 200) as int8 value in variable declaration (overflows)

With variables, by contrast, arithmetic simply wraps around at run time (see basic types). A compile-time check is one more reason to prefer constants for fixed values.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is a valid constant declaration?

    Constants must be computable at compile time, and only booleans, numbers and strings can be constants. Slices, maps and function calls like time.Now() cannot.
  2. 2. Given const c = 5, which of these compile? var a float64 = c and var b uint8 = c

    An untyped constant adapts to the type it is assigned to, as long as the value fits. 5 fits both float64 and uint8.
  3. 3. What do A, B and C hold? const ( A = iota + 1; B; C )

    The expression iota + 1 is repeated for B and C, and iota increases by one per line, giving 1, 2 and 3.
  4. 4. What is the value of Execute? const ( Read = 1 << iota; Write; Execute )

    Read is 1 << 0 = 1, Write is 1 << 1 = 2, and Execute is 1 << 2 = 4.
  5. 5. Why is giving an iota enum its own defined type (like type Weekday int) a good idea?

    A defined type gives the values a name and a method set, and the compiler rejects variables of other integer types where a Weekday is expected.

Summary

  • Declare constants with const, singly or in a group. Their value must be known at compile time, and only booleans, numbers, runes and strings qualify.
  • An untyped constant has a kind but no type and adapts to the context; typed constants behave like variables of that type. Untyped constants default to int, float64, rune, string or bool.
  • Constant expressions are evaluated at compile time with arbitrary precision; overflow is only checked when the value is stored in a typed variable.
  • iota numbers the lines of a const group from 0 and repeats the previous expression, which is how Go writes enums, offsets, bit flags and byte sizes.
  • Give enums a defined type and a String() method, and consider making 0 mean "unknown".

Next: Basic Types