We made it through all the conversion rules! Let’s change gear and talk about…

## Constant expressions

Constant expressions may contain only constant operands and are evaluated at compile time.

Or framed differently: Any expression that contains non-constant operands, is *not* a constant expression.

If you have a constant expression (e.g. `1 + 2`

) then extend it with a non-constant operand (e.g. `1 + 2 + userCount()`

), then it is no longer a constant expression.

(Actually, in this example, we have a non-constant expression made up of two operands, one of which is itself a constant expression `1 + 2`

, and the other which is the non-constant expression `userCount()`

).

Untyped boolean, numeric, and string constants may be used as operands wherever it is legal to use an operand of boolean, numeric, or string type, respectively.

A constant comparison always yields an untyped boolean constant. If the left operand of a constant shift expression is an untyped constant, the result is an integer constant; otherwise it is a constant of the same type as the left operand, which must be of integer type.

Any other operation on untyped constants results in an untyped constant of the same kind; that is, a boolean, integer, floating-point, complex, or string constant. If the untyped operands of a binary operation (other than a shift) are of different kinds, the result is of the operand’s kind that appears later in this list: integer, rune, floating-point, complex. For example, an untyped integer constant divided by an untyped complex constant yields an untyped complex constant.

All of this is just to explain the resulting type of a constant expression, which matters when composing complex expressions, or assigning to a variable, for example.

We’ll end today with a long table of examples:

`const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant) const b = 15 / 4 // b == 3 (untyped integer constant) const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant) const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division) const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division) const d = 1 << 3.0 // d == 8 (untyped integer constant) const e = 1.0 << 3 // e == 8 (untyped integer constant) const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32) const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant) const h = "foo" > "bar" // h == true (untyped boolean constant) const j = true // j == true (untyped boolean constant) const k = 'w' + 1 // k == 'x' (untyped rune constant) const l = "hi" // l == "hi" (untyped string constant) const m = string(k) // m == "x" (type string) const Σ = 1 - 0.707i // (untyped complex constant) const Δ = Σ + 2.0e-4 // (untyped complex constant) const Φ = iota*1i - 1/1i // (untyped complex constant)`

Quotes from *The Go Programming Language Specification* Language version go1.22 (Feb 6, 2024)