我试图在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",
}
Run Code Online (Sandbox Code Playgroud)
这是错误
# command-line-arguments
./Roman_Numerals.go:9: syntax error: unexpected {
Run Code Online (Sandbox Code Playgroud)
squ*_*guy 135
你的语法不正确.要制作文字地图(作为伪常量),您可以:
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",
}
Run Code Online (Sandbox Code Playgroud)
func你可以在里面声明它:
romanNumeralDict := map[int]string{
...
Run Code Online (Sandbox Code Playgroud)
在Go中,没有恒定的地图.更多信息可以在这里找到.
Sal*_*ali 20
您可以通过多种不同方式创建常量:
const myString = "hello"
const pi = 3.14 // untyped constant
const life int = 42 // typed constant (can use only with ints)
Run Code Online (Sandbox Code Playgroud)
您还可以创建枚举常量:
const (
First = 1
Second = 2
Third = 4
)
Run Code Online (Sandbox Code Playgroud)
你不能创建地图,数组的常量,它是有效写的:
Go中的常量只是常数.它们是在编译时创建的,即使在函数中定义为locals时也是如此,并且只能是数字,字符(符文),字符串或布尔值.由于编译时限制,定义它们的表达式必须是常量表达式,可由编译器评估.例如,1 << 3是常量表达式,而math.Sin(math.Pi/4)不是因为函数调用math.Sin需要在运行时发生.
ole*_*ber 10
您可以使用闭包模拟地图:
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))
}
Run Code Online (Sandbox Code Playgroud)
正如Siu Ching Pong -Asuka Kenji上面所建议的,我认为该函数更有意义,并且可以让您在没有函数包装器的情况下享受地图类型的便利:
// 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)
}
Run Code Online (Sandbox Code Playgroud)