How to declare a constant map in Golang?
I am trying to declare to constant in Go, but it is throwing an error. Could anyone please help me with the syntax of declaring a constant in Go?
This is my code:
const romanNumeralDict map[int]string = {
1000: "M",
900 : "CM",
500 : "D",
400 : "CD",
100 : "C",
90 : "XC",
50 : "L",
40 : "XL",
10 : "X",
9 : "IX",
5 : "V",
4 : "IV",
1 : "I",
}
This is the error
# command-line-arguments
./Roman_Numerals.go:9: syntax error: unexpected {
Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:
var romanNumeralDict = map[int]string{
1000: "M",
900 : "CM",
500 : "D",
400 : "CD",
100 : "C",
90 : "XC",
50 : "L",
40 : "XL",
10 : "X",
9 : "IX",
5 : "V",
4 : "IV",
1 : "I",
}
Inside a func
you can declare it like:
romanNumeralDict := map[int]string{
...
And in Go there is no such thing as a constant map. More information can be found here.
Try it out on the Go playground.
You can create constants in many different ways:
const myString = "hello"
const pi = 3.14 // untyped constant
const life int = 42 // typed constant (can use only with ints)
You can also create a enum constant:
const (
First = 1
Second = 2
Third = 4
)
You can not create constants of maps, arrays and it is written in effective go:
Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.