在范围循环中从Golang地图中删除所选的键是否安全? [英] Is it safe to remove selected keys from Golang map within a range loop?

查看:158
本文介绍了在范围循环中从Golang地图中删除所选的键是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Golang地图中删除所选的键?
是否可以将delete()与范围相结合,如下面的代码?

How can one remove selected keys from a Golang map? Is it safe to combine delete() with range, as in the code below?

http://play.golang.org/p/u1vufvEjSw

package main

import "fmt"

type Info struct {
    value string
}

func main() {
    table := make(map[string]*Info)

    for i := 0; i < 10; i++ {
        str := fmt.Sprintf("%v", i)
        table[str] = &Info{str}
    }

    for key, value := range table {
        fmt.Printf("deleting %v=>%v\n", key, value.value)
        delete(table, key)
    }
}


推荐答案

这是安全的!您还可以在 Effective Go 中找到类似的示例:

This is safe! You can also find a similar sample in Effective Go:

for key := range m {
    if key.expired() {
        delete(m, key)
    }
}

语言规范


地图上的迭代顺序未指定,不是保证从一个迭代到下一个迭代相同。如果尚未达到的映射条目在迭代 中删除,则不会生成相应的迭代值。如果映射条目在迭代期间创建 ,则可能会在迭代期间生成该条目,也可能会被跳过。每个创建的条目和从一个迭代到下一个条目的选择可能会有所不同。如果地图为零,迭代次数为0。

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If map entries that have not yet been reached are removed during iteration, the corresponding iteration values will not be produced. If map entries are 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.

这篇关于在范围循环中从Golang地图中删除所选的键是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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