英文:
Golang : for loop over map goes into infinite loop even after value is updated
问题
package main
import "fmt"
func main() {
mapVal := map[string]string{
"a": "k",
}
a := []string{"a", "b"}
for i := range a {
for _, ok := mapVal[a[i]]; ok; {
i++
fmt.Printf("i 的值为 %d", i)
}
}
}
我在这段代码中使用了一个嵌套循环 _, ok := mapVal[a[i]]; ok;
。在第一次迭代中,i 等于 0,a[0] 等于 "a",返回的值(_) 和 ok(bool) 都为 true。但是在第二次迭代中,i 被递增为 1,a1 等于 "b",这意味着 ok(bool) 应该为 false,但实际上返回的是 true,导致循环无限进行下去。
英文:
package main
import "fmt"
func main() {
mapVal := map[string]string{
"a": "k",
}
a := []string{"a", "b"}
for i := range a {
for _, ok := mapVal[a[i]]; ok; {
i++
fmt.Printf("the value of i is %d", i)
}
}
}
I did loop over the map which is a nested loop _, ok := mapVal[a[i]]; ok;
. For the first iteration i equals to 0 and a[0] == "a" which returns the value(_) and ok(bool) as true but for the second iteration value i is incremented and i equals to 1 and a1 == "b" which means the ok(bool) should be false but it is returned as true and the loop goes for infinite.
答案1
得分: 3
你在内部循环中使用了一个传统的for循环。
它的格式如下:
for i := 0; i < 10; i++ {
}
i := 0
是 InitStmt
,i < 10
是 Condition
,i++
是 PostStmt
。PostStmt
在每次循环迭代时执行。
在你的情况下,mapVal
的访问是 InitStmt
的一部分,而 ok
是 Condition
的一部分,但没有 PostStmt
。
因此,由于 InitStmt
只在循环开始时运行一次,ok
的值永远不会改变。
英文:
You are using a traditional for loop in the inner loop.
It has the format:
for i := 0; i < 10; i++ {
}
i := 0
is the InitStmt
, i < 10
is the Condition
, and i++
is the PostStmt
. The PostStmt
is run every loop iteration.
In your case, the mapVal
access is a part of the InitStmt
and the ok
is a part of the Condition
, but there is no PostStmt
.
So, because the InitStmt
is only run once at the beginning of the for loop, the value of ok
never changes.
答案2
得分: 0
问题出在你的内部循环上。它没有重新分配ok的值以供下一次使用,如果它一次评估为true,就会进入无限循环。这是我更新后的代码:
package main
import "fmt"
func main() {
mapVal := map[string]string{
"a": "k",
}
a := []string{"a", "b"}
for i := range a {
for _, ok := mapVal[a[i]]; ok; {
i++
fmt.Printf("i的值为%d\n", i)
_, ok = mapVal[a[i]]
}
}
}
请注意,我只翻译了代码部分,其他内容不做翻译。
英文:
Issue is with your inner loop. It does not reassign the value of ok for next time and if it evaluates true once, it goes into infinite loop. Here is my updated:
package main
import "fmt"
func main() {
mapVal := map[string]string{
"a": "k",
}
a := []string{"a", "b"}
for i := range a {
for _, ok := mapVal[a[i]]; ok; {
i++
fmt.Printf("the value of i is %d\n", i)
_, ok = mapVal[a[i]]
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论