How to Declare a Constant Map in Golang

In Go, you cannot directly declare a map as a constant because maps are reference types, and their contents are mutable. However, there is a workaround, like an “anonymous function”, that you can use to create a constant map-like object.

An anonymous function is a function that is defined inline without a name. Anonymous functions can create closures, variables bound to the function’s context.

Example 1

package main

import "fmt"

func main() {
  readOnlyMap := GetReadOnlyMap()

  value, ok := readOnlyMap["key1"]
  if ok {
    fmt.Printf("Value of key1: %s\n", value)
  } else {
    fmt.Println("Key not found")
  }
}
func GetReadOnlyMap() map[string]string {
  readOnly := map[string]string{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
  }
  return readOnly
}

Output

Value of key1: value1

In this example, the GetReadOnlyMap() function returns a map with predefined key-value pairs.

You can use this function to get a read-only map. Although you cannot enforce immutability, you can treat the map as read-only and avoid modifying it.

Remember that it’s up to the developer to make sure the map is treated as read-only, and the compiler won’t enforce this constraint.

Example 2

package main

import (
  "fmt"
)

var daysOfWeek = map[int]string{
  1: "Sunday",
  2: "Monday",
  3: "Tuesday",
  4: "Wednesday",
  5: "Thursday",
  6: "Friday",
  7: "Saturday",
}

func GetDay(index int) string {
  return daysOfWeek[index]
}

func GetDaysOfWeekCopy() map[int]string {
  copyMap := make(map[int]string)
  for k, v := range daysOfWeek {
    copyMap[k] = v
  }
  return copyMap
}

func main() {
  day := GetDay(3)
  fmt.Println(day)

  copyOfDays := GetDaysOfWeekCopy()
  fmt.Println(copyOfDays)
}

Output

Tuesday
map[1:Sunday 2:Monday 3:Tuesday 4:Wednesday 5:Thursday 6:Friday 7:Saturday]

That’s it!