HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to declare a constant map in Golang?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
constanthowdeclaregolangmap

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

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.

Context

Stack Overflow Q#18342195, score: 283

Revisions (0)

No revisions yet.