The Avid Gopher

Constant array

Constants are basically variables whose value can’t change and they are helping us to write safer and cleaner code. But exists something like constant arrays in Go?

Some basic constants

The declaration and initialisation of some basic constants works flawlessly and is no problem (as expected):

1
2
3
const foo = "Hello World"
const bar = 1
const qux = 0.7

Constant arrays/slices

Sometimes our coder’s mind is pining for constant arrays and we are trying to convince Go with various phrasings:

1
2
3
4
const numbers = { 5, 9, 7 }
const numbers []int = { 5, 9, 7 }
const numbers = []int { 5, 9, 7 }
const numbers = [3]int { 5, 9, 7 }

But Go’s compiler keeps refusing our delightful lines of code:

1
2
3
syntax error: unexpected {, expecting expression
const initializer []int literal is not a constant
const initializer [3]int literal is not a constant

Why could I not declare and initialise a const array of integers?

Constants and constant expressions

Constants reference a scalar value by a name and get evaluated at compile time. By this only numbers, strings, etc. can be constant.

But let me cite more precisely from Go’s reference docs regarding constants:

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

There exists even something named constant expressions, which are expressions that are built from constants itself. More details and examples can be found at Go’s spec on constant expressions:

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

What about […]T?

1
const numbers [...]int  = { 5, 9, 7 }

Even the [...]T syntax is just syntactic sugar for [123]T. It creates a fixed size array, but lets the compiler figure out how many elements are in it.

The solution

There is no real solution as it is not possible. But an alternative would be something like this:

1
var numbers = [...]int { 5, 9, 7 }

There is also a great blog post at the Go blog about constants.