<分区>
Go 没有数组常量。
我的应用程序收到的消息包含多种类型的数字代码,我需要将其显示为短语。
如果存在数组内容,我可以这样做:
func foo() {
...
fmt.Println(facename[f])
...
}
const facename [...]string = "top", "bottom", "left", "right", "front", "back"
但是当然没有办法做到这一点。我想到的第一种解决方法,也许是一种合理有效的方法是使用 switch
func foo() {
...
name := "unknown"
switch f {
case 0:
name = "top"
case 1:
name = "bottom"
case 2:
name = "left"
case 3:
name = "right"
case 4:
name = "front"
case 5:
name = "back"
}
fmt.Println(name)
...
}
如果值的数量达到 20 个或更多,则上述内容相当乏味。
看起来最简洁的方式是这样的
func foo() {
...
fmt.Println(strings.Split(facenames,",")[f])
...
}
const facenames = "top,bottom,left,right,front,back"
当然,我还必须检查索引是否在范围内。
尽管目前效率不是问题,但让我感到困扰的是
我使用 strings.Split()
的次数超出了我的预期。
是否有另一种既符合习惯又简洁高效的方式?