如何在golang中声明常量映射

我是golang的新手。 我正在努力申明不断的走下去。 但是这是一个错误。 任何人都可以请帮助我的语法去声明一个常量吗?

这是我的代码:

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 { 

你的语法不正确。 要创build一个文字图(作为一个伪常量),你可以这样做:

 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{ ... 

在Go中没有像恒定的地图那样的东西。 更多信息可以在这里find。

试试看在操场上。

您可以用许多不同的方式创build常量:

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

你也可以创build一个枚举常量:

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

你不能创build地图,数组的常量,它是写在有效的去 :

Go中的常量只是常数。 它们是在编译时创build的,即使在函数中定义为locals,也只能是数字,字符(符文),string或布尔值。 由于编译时限制,定义它们的expression式必须是常量expression式,可由编译器进行评估。 例如,1 << 3是一个常量expression式,而math.Sin(math.Pi / 4)并不是因为函数调用math.Sin需要在运行时发生。

您可以使用闭包来模拟地图:

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

试试在操场上

如上所述将地图定义为常量是不可能的。 但是你可以声明一个全局variables,它是一个包含地图的结构。

初始化看起来像这样:

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