Go: multiple keys to single value in map

huangapple go评论69阅读模式
英文:

Go: multiple keys to single value in map

问题

在Go语言中,地图的键不能包含OR运算符。在你提供的示例中,使用OR运算符(||)将导致错误。地图的键必须是一个单独的值,不能是表达式或运算符的组合。如果你需要将多个键映射到相同的值,你可以考虑使用其他的数据结构或者重新设计你的代码逻辑来实现你的需求。

英文:

Is it possible to include an OR operator in the key of a map? Eg.

Go:

var a = map[string]int{
    "A1"|| "B1": 1,
    "A2": 2,
}

Error:

invalid operation: "A1" || "B1" (operator || not defined on string)

答案1

得分: 8

不,你不能。语法在http://golang.org/ref/spec#Composite_literals中定义,并不包括这个特性。你需要明确指定每个键。

英文:

No, you cannot. The grammar is defined at http://golang.org/ref/spec#Composite_literals and does not include this feature. You will have to specify each key distinctly.

huangapple
  • 本文由 发表于 2014年11月19日 22:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/27019999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定