如何在范围循环中添加到地图 [英] How to add into map in range loop

查看:80
本文介绍了如何在范围循环中添加到地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.视频是此处 playgroud

This code returns: 8 or 10 or 6 as length of map after loop. Video is here, playgroud here.

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

I see that new added elements go into range, but can't explain why this loop stops randomly?

推荐答案

说明:声明:

未指定映射的迭代顺序,并且不能保证每次迭代之间都相同.如果在迭代过程中删除了尚未到达的映射条目,则不会生成相应的迭代值.如果在迭代过程中创建了地图条目,则该条目可能会在迭代过程中产生或被跳过.对于每个创建的条目以及从一个迭代到下一个迭代,选择可能会有所不同.如果映射为nil,则迭代次数为0.

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.

该规范指出,如果您将要添加的条目添加到地图中,则循环可能会或不会访问您添加的元素,此外,被访问的元素甚至无法确定(再次执行时可能会更改)).

The spec states that if you add entries to the map you are ranging over, the elements you add may or may not be visited by the loop, and moreover, which is visited is not even deterministic (may change when doing it again).

这篇关于如何在范围循环中添加到地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆