dongren7374 2014-04-22 20:52
浏览 49
已采纳

在范围循环内从地图中删除选定的键是否安全?

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
", key, value.value)
        delete(table, key)
    }
}

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

  • 写回答

4条回答 默认 最新

  • dongzhenju3015 2014-04-22 21:19
    关注

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

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

    And the language specification:

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题