我试图在Go中声明为constant,但它抛出了一个错误。有人能帮助我在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 {
发布于 2014-12-13 16:55:30
您可以使用闭包来模拟地图:
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))
}
发布于 2018-01-18 13:40:36
正如上面Siu Ching Pong -Asuka Kenji使用函数所建议的那样,在我看来,这更有意义,并且让您可以方便地使用map类型,而不需要函数包装器:
// 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)
}
发布于 2016-09-03 22:30:17
如上所述,将映射定义为常量是不可能的。但是您可以声明一个全局变量,它是一个包含map的结构。
初始化将如下所示:
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])
}
https://stackoverflow.com/questions/18342195
复制相似问题