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 be used to create closures, which are variables that are bound to the context of the function.

Example

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.

Leave a Comment