How to Create a Constant Array in Golang

You cannot create a constant array in Go because arrays are mutable data structures, and constants can only store immutable values. However, you can create a variable array and use it as a read-only array using the “[…]” syntax, which allows the Go compiler to infer the array’s length based on the number of elements you provide during initialization.

Arrays with constant values can be created, but the array cannot be constant because Go doesn’t support constant arrays or slices.

When you use […] in an array declaration, you’re telling the Go compiler to determine the array length automatically based on the number of elements you provide during initialization.

package main

import (
  "fmt"
)

var daysOfWeek = [...]string{
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
}

func main() {
  fmt.Println("Days of the week:")
  for _, day := range daysOfWeek {
    fmt.Println(day)
  }
}

Output

Days of the week:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

In this code example, we used the […] expression specifying the array’s length. The Go compiler infers the size based on the number of elements provided during initialization.

You can also define a fixed length of an array instead of […].

var daysOfWeek = [7]string{
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
}

In this example, we created a variable array, daysOfWeek, containing the days of the week. Although it is not a constant, we can use it as a read-only array and avoid modifying it. When using this array, treat it as a read-only constant in your code.

Creating a Constant Array of Integers

Only integer values can be made constant with “iota”. If you need constant arrays of other types, you can use the above approach.

package main

import (
  "fmt"
)

const (
  Zero = iota
  One
  Two
  Three
)

func main() {
  constArray := [4]int{Zero, One, Two, Three}
  fmt.Println(constArray)
}

Output

[0 1 2 3]

That’s it.