Golang:即使更新了值,对映射进行的for循环进入无限循环

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

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 := 0InitStmti < 10Conditioni++PostStmtPostStmt 在每次循环迭代时执行。

在你的情况下,mapVal 的访问是 InitStmt 的一部分,而 okCondition 的一部分,但没有 PostStmt

因此,由于 InitStmt 只在循环开始时运行一次,ok 的值永远不会改变。

英文:

You are using a traditional for loop in the inner loop.

It has the format:

for i := 0; i &lt; 10; i++ {
}

i := 0 is the InitStmt, i &lt; 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 &quot;fmt&quot;

func main() {

	mapVal := map[string]string{
		&quot;a&quot;: &quot;k&quot;,
	}
	a := []string{&quot;a&quot;, &quot;b&quot;}

	for i := range a {
		for _, ok := mapVal[a[i]]; ok; {
			i++
			fmt.Printf(&quot;the value of i is %d\n&quot;, i)
			_, ok = mapVal[a[i]]
		}
	}

}

huangapple
  • 本文由 发表于 2023年3月17日 10:27:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75763271.html
匿名

发表评论

匿名网友

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

确定