英文:
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
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论