How to declare a constant map in Golang?

前端 未结 5 1830
清歌不尽
清歌不尽 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:13

    And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:

       // romanNumeralDict returns map[int]string dictionary, since the return
           // value is always the same it gives the pseudo-constant output, which
           // can be referred to in the same map-alike fashion.
           var romanNumeralDict = func() map[int]string { return 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",
              }
            }
    
            func printRoman(key int) {
              fmt.Println(romanNumeralDict()[key])
            }
    
            func printKeyN(key, n int) {
              fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
            }
    
            func main() {
              printRoman(1000)
              printRoman(50)
              printKeyN(10, 3)
            }
    

    Try this at play.golang.org.

提交回复
热议问题