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 .

Related Content


Constant errors

Last week I talked about how to create your own errors. Expanding on that idea, here’s a trick I like to use: Constant errors! Constants in Go are limited to simple underlying types: bool, string, and the numeric types. If we create our own type, which both satisfies the error interface, and has such an underlying type, we can then create constant error values: type errString string func (e errString) Error() string { return string(e) } const ErrTooManyFrogs = errString("too many frogs") Okay.


Constant lengths and expressions

A few of the built-in functions are very special, in that they can evaluate to constant expressions. len and cap are two such functions. But they aren’t always evaluated to constant expressions, sometimes they’re more normal-ish runtime functions. Length and capacity … The expression len(s) is constant if s is a string constant. The expressions len(s) and cap(s) are constants if the type of s is an array or pointer to an array and the expression s does not contain channel receives or (non-constant) function calls; in this case s is not evaluated.


Constant expressions, part III

Did you miss yesterday’s Ask-me-anything session? You probably did. I had about 10-15 people there. But even with a small group, we had a ton of great questions! The Q&A session lasted about an hour, and covered topics such as book recommendations for going deeper into Go, what project to build to learn concurrency, and much more. Catch the replay on YouTube. Let’s continue our discussion of constant expressions, with some more miscellaneous rules:

Get daily content like this in your inbox!

Subscribe