how to iterate a map with its key/value with a count just like "i ++" in the "for" statement

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

how to iterate a map with its key/value with a count just like "i ++" in the "for" statement

问题

我正在使用Go语言,并且我想遍历一个地图,同时遍历它的键和值,同时我还想计算地图中的项目数量。

我尝试了这个:

  for i := 0; k,v := range map; i++ { }

我只想知道for ...范围语句是否可以与i++一起使用,i++for语句的常规部分。

英文:

I am using go language and I want to iterate a map with its keys and values all over a map,
at the same time, I also want to count the number of items in the map

I tried this:

  for i := 0; k,v := range map; i++ { }

I just want to know if for ... range statement can work with i++ which is usual part of
for statement

答案1

得分: 3

当你尝试时,你会发现那是行不通的。你必须将其明确写出:

i := 0
for k, v := range someMap {
    //...
    i++
}
英文:

As you must have discovered when you tried it, that doesn't work. You have to just spell it out:

i := 0
for k, v := range someMap {
    //...
    i++
}

答案2

得分: 1

range子句for语句中不允许这样做。你必须这样写:

var i int
for k, v := range myMap {
        whatever()
        i++
}

请注意,如果在迭代过程中不改变映射,则之后

i == len(myMap)

是正确的。

英文:

The range clause of the for statement doesn't allow this. You have to write, for example:

var i int
for k, v := range myMap {
        whatever()
        i++
}

Note that if you don't mutate the map while iterating over it then

i == len(myMap)

is true afterwards.

huangapple
  • 本文由 发表于 2013年7月10日 16:57:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/17566369.html
匿名

发表评论

匿名网友

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

确定