Constants
There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.
So there we have it. A comprehensive list of the available constant types in Go. And all but boolean
and string
constants are numeric.
Notice that none of the composite types can be constants in Go. You can’t have a constant array, slice, struct, or interface.
A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as
unsafe.Sizeof
applied to certain values,cap
orlen
applied to some expressions,real
andimag
applied to a complex constant andcomplex
applied to numeric constants. The boolean truth values are represented by the predeclared constantstrue
andfalse
. The predeclared identifier iota denotes an integer constant.In general, complex constants are a form of constant expression and are discussed in that section.
Okay, wow. There’s a lot in that section. But it’s not that complex. In summary, a constant value is represented by:
-
An appropriate literal
const x = 123 // A numeric literal
-
An identifier denoting another constant
const x = 123 const y = x // x is an identifier denoting a constant
-
A constant expression (which we’ll discuss into later)
const x = 1 + 2 + 3 // a constant expression
-
A conversion, with a constant result
const x = int(123) // x is an integer constant const y = int64(x) // int64(x) converts x to an int64, and has a constant result
-
Or the result of some built-in functions such as
unsafe.Sizeof
,len
, orcap
.x := [3]int{} // x is an array of int, with length 3 const y = len(x) // Although x is not a constant, the result of len(x) is, // because it is known at compile time.
We’ll talk more about the boolean constant values, and the special constant iota
in the future.
Quotes from The Go Programming Language Specification, Version of June 29, 2022