In this guide, we will learn how to define the constant arrays in the Go programming language. This allows you to store a collection of values that cannot be changed in a single unit.
What Is a Constant Array?
As the name suggests, a constant array is an array whose elements are predefined as constant during compile time.
Hence, once we declare an array as constant, we cannot change its elements during runtime which provides immutability, compile-time safety, and performance benefits (in some cases).
Declare a Const Array in Golang
Unfortunately, we cannot directly declare an array as constant since arrays are mutable data structures. Since we can only set the constant property to immutable values, it means that we have to implement a custom feature to work with constant arrays.
The most efficient technique of defining a constant array in Go is using the […] syntax. This allows the compiler to infer the length of the array based on the number of elements during initialization.
import (
"fmt"
)
var addresses = [...]string{
"localhost:3306",
"localhost:4453",
"development.remote:6379",
}
func main() {
fmt.Println("Days of the week:")
for _, addr := range addresses {
fmt.Println(addr)
}
}
In this case, we are using the […] expression to tell the compiler to infer the size of the array based on the number of elements.
NOTE: It is good to understand that this does not mean that the array is a constant. However, it depicts the read-only properties which prevent the modification. However, it is up to you to ensure that the array is read-only within your code.
Array of Integers
If you need to create a constant-like array of integers, we can use the “iota” keyword. This allows us to declare a sequence of incrementing integers within constant declaration.
An example usage is as follows:
import (
"fmt"
)
const (
Zero = 10 + iota
One
Two
Three
)
func main() {
constArray := [4]int{Zero, One, Two, Three}
fmt.Println(constArray)
}
This basically creates a series of constant integers and treats them as an array.
Conclusion
In this tutorial, we learned how we can implement a constant-like array in Go by setting the read-only properties to the array. Keep in mind that you cannot declare an array as constant since it is a mutable data structure.