gpt4 book ai didi

loops - 如何在范围循环中添加到 map 中

转载 作者:IT王子 更新时间:2023-10-29 01:56:23 25 4
gpt4 key购买 nike

package main

import (
"fmt"
)

func main() {
m := make(map[int]int, 4)
m[1] = 0
m[2] = 0
for k, _ := range m {
i := 10 + k
m[i] = 0
}
fmt.Println(m)
fmt.Println("len:", len(m))
}

此代码返回:8 或 10 或 6 作为循环后 map 的长度。视频是here , Playground here .

我看到新添加的元素进入了范围,但无法解释为什么这个循环随机停止?

最佳答案

Spec: For statements:

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.

规范指出,如果您将条目添加到您正在测距的 map 中,您添加的元素可能会或可能不会被循环访问,而且,被访问的元素甚至不是确定性的(再次执行时可能会改变).

关于loops - 如何在范围循环中添加到 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55399243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com