Published: March 4, 2019
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):
|
|
Constant arrays/slices
Sometimes our coder’s mind is pining for constant arrays and we are trying to convince Go with various phrasings:
|
|
But Go’s compiler keeps refusing our delightful lines of code:
|
|
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?
|
|
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:
|
|
There is also a great blog post at the Go blog about constants.