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

Related Content

Empty structs

We finally we have enough knowledge for the EBNF format not to seem completely foreign, so let’s jump back and take a look at that, with the examples provided in the spec… Struct types … StructType = "struct" "{" { FieldDecl ";" } "}" . FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] . EmbeddedField = [ "*" ] TypeName [ TypeArgs ] . Tag = string_lit . // An empty struct.

Struct tags

Struct types … A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored. struct { x, y float64 "" // an empty tag string is like an absent tag name string "any string is permitted as a tag" _ [4]byte "ceci n'est pas un champ de structure" } // A struct corresponding to a TimeStamp protocol buffer.

Struct method promotion

Yesterday we saw an example of struct field promotion. But methods (which we haven’t really discussed yet) can also be promoted. Struct types … Given a struct type S and a named type T, promoted methods are included in the method set of the struct as follows: If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.