在 Golang 中检查字典键是否存在的布尔条件的右侧。

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

Checking Dictionary Key Existence in Golang on right side of boolean condition

问题

我有一个包含地图的数组,在golang中,我正在遍历列表,并需要检查当前迭代中的键是否存在于列表中的下一个地图中,我知道检查元素是否存在于地图中的常规方法是这样做:

  1. if _, ok := m[key]; ok {
  2. ...
  3. }

但是有没有一种方法可以这样做?

  1. if index < len(arr)-1 && (_, ok := arr[index+1][key]; ok) {
  2. ...
  3. }

其中短路计算可以起作用,并且代码保持在一行中?

英文:

I have an array of maps in golang, I'm iterating over the list and need to check if a key from the current iteration exists in the next map in the list, I know the normal way to check if an element exists in a map is to do:

  1. if _, ok := m[key]; ok {
  2. ...
  3. }

but is there a way to do this?

  1. if index &lt; len(arr)-1 &amp;&amp; (_, ok := arr[index+1][key]; ok) {
  2. ...
  3. }

where short-circuiting would work and the code remains in one line?

答案1

得分: 2

据我所知,没有一种方法可以在一行中完成这个操作。

嘿,Go语言甚至没有?:运算符

> Go语言中没有 ?: 的原因是,语言设计者发现该操作经常被用于创建难以理解的复杂表达式。if-else形式虽然更长,但无疑更清晰。一种语言只需要一种条件控制流构造。

而且,Go语言的一条格言是清晰胜于巧妙

所以不要费力去做这个。就像这样写:

  1. if index < len(arr)-1 {
  2. if _, ok := arr[index+1][key]; ok {
  3. //...
  4. }
  5. }

关于你遍历列表的问题,也许这样写更好:

  1. // 假设arr至少有1个元素
  2. for index := range arr[0 : len(arr)-1] {
  3. if _, ok := arr[index+1][key]; ok {
  4. //...
  5. }
  6. }
英文:

AFAIK, there is no way to do it in one line.

Hey, Go even does not have the ?: operator:

> The reason ?: is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

And one of Go's proverbs is Clear is better than clever.

So don't struggle with it. Just write it like this:

  1. if index &lt; len(arr)-1 {
  2. if _, ok := arr[index+1][key]; ok {
  3. //...
  4. }
  5. }

Regarding you're iterating over the list, maybe it's better to write it like this:

  1. // assumes arr has at least 1 items
  2. for index := range arr[0 : len(arr)-1] {
  3. if _, ok := arr[index+1][key]; ok {
  4. //...
  5. }
  6. }

huangapple
  • 本文由 发表于 2023年7月19日 10:35:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76717612.html
匿名

发表评论

匿名网友

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

确定