如何在 Golang 声明一个常量 map?

我试图在 Go 中声明为常量,但它抛出了一个错误。有人能帮我解释一下在 Go 中声明常量的语法吗?

这是我的暗号:

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",
}

就是这个错误

# command-line-arguments
./Roman_Numerals.go:9: syntax error: unexpected {
200986 次浏览

您的语法不正确。要创建一个文本映射(作为伪常量) ,您可以这样做:

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",
}

func中,你可以这样声明:

romanNumeralDict := map[int]string{
...

在围棋中没有常量地图这样的东西。更多的信息可以找到 这里

在围棋场上试试。

你可以模拟一张带闭包的地图:

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))
}

在围棋场上试试

您可以通过许多不同的方式创建常量:

const myString = "hello"
const pi = 3.14 // untyped constant
const life int = 42 // typed constant (can use only with ints)

还可以创建一个枚举常量:

const (
First = 1
Second = 2
Third = 4
)

您不能创建映射、数组的常量,它是用 有效行动编写的:

Go 中的常量就是常量,它们是在编译时创建的 时间,即使在函数中定义为局部变量时,也只能是 数字、字符(如尼文)、字符串或布尔值 编译时限制,定义它们的表达式必须是 常量表达式,可由编译器计算 是一个常量表达式,而数学。 Sin (math.Pi/4)不是因为 对数学的函数调用。罪需要在运行时发生。

如上所述,将映射定义为常量是不可能的。 但是您可以声明一个全局变量,它是一个包含映射的结构。

初始化应该是这样的:

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])
}

正如上面 小青碰-明日香健二所建议的那样,这个函数在我看来更有意义,让你在没有函数包装的情况下,使用地图类型更加方便:

   // 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)
}

在 play.golang.org 上试试这个。