How to declare a constant map in Golang?

前端 未结 5 1874
清歌不尽
清歌不尽 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 15:55

    You may emulate a map with a closure:

    package main
    
    import (
        "fmt"
    )
    
    // http://stackoverflow.com/a/27457144/10278
    
    func romanNumeralDict() func(int) string {
        // innerMap is captured in the closure returned below
        innerMap := 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",
        }
    
        return func(key int) string {
            return innerMap[key]
        }
    }
    
    func main() {
        fmt.Println(romanNumeralDict()(10))
        fmt.Println(romanNumeralDict()(100))
    
        dict := romanNumeralDict()
        fmt.Println(dict(400))
    }
    

    Try it on the Go playground

提交回复
热议问题