How to declare a constant map in Golang?

前端 未结 5 1820
清歌不尽
清歌不尽 2021-01-30 15:30

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:

5条回答
  •  有刺的猬
    2021-01-30 16:01

    As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.

    The Initialization would look like this:

    var romanNumeralDict = struct {
        m map[int]string
    }{m: map[int]string {
        1000: "M",
        900: "CM",
        //YOUR VALUES HERE
    }}
    
    func main() {
        d := 1000
        fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
    }
    

提交回复
热议问题