Constant expressions, continued

March 18, 2024

Today I’ll be answering your questions on my weekly live stream. Have a question about Go? About CI/CD? About my favorite pizza toppings? Join me! Or submit your question early and catch the replay, if you can’t join live.


Today we continue the section on Constant expressions, with a grab bag of miscellaneous rules.

Constant expressions

Applying the built-in function complex to untyped integer, rune, or floating-point constants yields an untyped complex constant.

const ic = complex(0, c)   // ic == 3.75i  (untyped complex constant)
const iΘ = complex(0, Θ)   // iΘ == 1i     (type complex128)

You’ll almost certainly never use this. If you do, let me know! I have many questions for you! 😂

Now for something with more practical application, which we’ve already talked about once or twice. But here’s where it’s explicitly defined in the spec:

Constant expressions are always evaluated exactly; intermediate values and the constants themselves may require precision significantly larger than supported by any predeclared type in the language. The following are legal declarations:

const Huge = 1 << 100         // Huge == 1267650600228229401496703205376  (untyped integer constant)
const Four int8 = Huge >> 98  // Four == 4                                (type int8)

Now I think the word “exactly” is not always technically true. As dicsussed in the past, there may actually be a limit to the precision of integer constants of as “few” as 256 bits. This is close enough to “exact” for the vast majority of use cases, as rarely matter, though. And an implementation is free to use more than 256 bits, perhaps even an arbitrary number of bits, to truly offer exactness.

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


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe