Constants at compile time

February 1, 2023

Yesterday I made a passing comment in the last code example:

Although x is not a constant, the result of len(x) is, because it is known at compile time.

I want to dive into this aspect of constants in Go today.

In Go (or at least most, if not all implementations of Go) a constant is logically replaced during compilation. This can be a useful mental shortcut when trying to determine whether a given expression can be a constant or not.

In other words, this code:

const x = 123
if x > 10 {
  fmt.Println(x)
}

is effectively the same as:

if 123 > 10 {
  fmt.Println(123)
}

This is in contrast to languages like JavaScript, where const just means “a value that can’t be changed”. In Go, a constant can be thought of as more like a macro replacement.

In general, the concept of a “constant” in a compiled language is distinct from that in most interpreted languages, although implementations can and do vary.


Share this

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

Unsure? Browse the archive .