How to declare a constant map in Golang?

go

Solution

In Go, a map unfortunately cannot be `const`. You can declare it as a regular variable like this with the `var` keyword:

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

Inside a function, you may declare it with the short assignment syntax:

func main() {
    myMap := map[int]string{
        1: "one",
        2: "two",
        3: "three",
    }
}

Try it out on the Go playground.

Problem

I am trying to declare to constant in Go, but it is throwing an error. This is my code: ``` const myMap = map[int]string{ 1: "one", 2: "two", 3: "three", } ``` This is the error ``` map[int]string{…} (value of type map[int]string) is not constant ```

Original source

Related problems