为了账号安全,请及时绑定邮箱和手机立即绑定

如果它是字符串,数组不接受索引

如果它是字符串,数组不接受索引

Go
慕斯王 2022-07-25 11:21:11
这是我的示例,为什么第一个代码有效而第二个代码无效???此代码不起作用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 %v\n", 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 %v\n", entery, shortcuts[Egypt])}
查看完整描述

2 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

您可以使用关联映射,其中与映射中的键关联的值表示其在数组中的等效项的索引值。例如,

shortcuts := [...]string{"", "EG","GER","US"}
shortcutMap := map[string]int{"" : 0, "Egypt": 1, "Germany": 2, "UnitedStates": 3}

那应该允许您像这样调用shortcutMap:

shortcutMap["Egypt"]

并从那里找到快捷方式:

shortcuts[shortcutMap["Egypt"]]

将返回“EG”

对于您的问题,这不是一个很好的解决方案,因为它使添加和删除列表的快捷方式以及维护索引关联的键值变得复杂。但是您似乎想保留一系列快捷方式。正如有人已经说过的,数组只能用整数索引;打电话array["string"]永远不会奏效。


查看完整回答
反对 回复 2022-07-25
?
12345678_0001

TA贡献1802条经验 获得超5个赞

你有点回答了标题中的问题。os.Args[0/1/2...] 返回一个字符串。

https://golang.org/pkg/os/#Variables

数组索引不能是字符串。不在 Go 语言中。或我知道的任何其他语言。


查看完整回答
反对 回复 2022-07-25
  • 2 回答
  • 0 关注
  • 142 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号