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

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

问题描述

一个人如何从地图中删除选定的键? 如下面的代码所示,将delete()与范围结合使用是否安全?

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

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)
    }
}

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

推荐答案

这很安全!您还可以在有效的Go

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

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

语言规范:

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

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

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