Sobes.tech
Senior

Is it possible to make memory constant without removing the map?

sobes.tech AI

Answer from AI

In Go, it is not possible to make a map completely constant because the built-in map type is mutable and does not support constants directly. However, you can achieve a "constant" memory effect with a map if:

  • Initialize the map once and do not modify it afterwards (do not add or remove elements).
  • Make the map private and provide only read methods, without methods for modification.

Example:

var constMap = map[string]int{
    "one": 1,
    "two": 2,
}

func GetValue(key string) (int, bool) {
    val, ok := constMap[key]
    return val, ok
}

Thus, although the map is not a constant, restricting access to it only for reading essentially makes it "constant" memory without deleting the map.

Is it possible to make memory constant without… - sobes.tech