这是我的示例,为什么第一个代码有效,而第二个代码无效???
此代码不工作
func main() {
type Country int
const (
Egypt Country = iota
Germany
UnitedStates
)
shortcuts := [...]string{Egypt: "EG", Germany: "GER", UnitedStates: "US"}
fmt.Println("Please use one of these [ 'Egypt', 'Germany', 'UnitedStates']")
entery := os.Args[1]
fmt.Printf("The short cut of %v is %vn", entery, shortcuts[entery])
}
此代码正在运行
func main() {
type Country int
const (
Egypt Country = iota
Germany
UnitedStates
)
shortcuts := [...]string{Egypt: "EG", Germany: "GER", UnitedStates: "US"}
fmt.Println("Please use one of these [ 'Egypt', 'Germany', 'UnitedStates']")
entery := os.Args[1]
fmt.Printf("The short cut of %v is %vn", entery, shortcuts[Egypt])
}
您可以使用关联映射,其中映射中与键关联的值表示数组中等价键的索引值。例如,
shortcuts := [...]string{"", "EG","GER","US"}
shortcutMap := map[string]int{"" : 0, "Egypt": 1, "Germany": 2, "UnitedStates": 3}
这应该允许你这样调用shortcutMap:
shortcutMap["Egypt"]
从那里找到快捷方式:
shortcuts[shortcutMap["Egypt"]]
将返回";EG";
这并不能很好地解决您的问题,因为它会使添加和删除列表的快捷方式以及维护索引关联的键值变得复杂。但你似乎想保留快捷方式的数组。正如有人已经说过的,数组只能用整数进行索引;调用CCD_ 1将永远不起作用。
您在某种程度上回答了标题中的问题。os。Args[0/1/2…]返回一个字符串。
https://golang.org/pkg/os/#Variables
数组索引不能是字符串。戈朗没有。或者我知道的任何其他语言。