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 […], which allows the Go compiler to infer the array’s length based on the number of elements you provide during initialization.

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.

This is helpful when you don’t want to specify the array’s length explicitly.

Example

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

We used the […] expression specifying the array’s length in this code example. The Go compiler infers the length 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.

That’s it.

Leave a Comment