douchen4547 2018-05-14 04:34
浏览 25
已采纳

golang取消引用地图

Here is a sample code that creates a Map of string keys having value of bool.

myMap := make(map[string]bool)

myMap["Jan"] = true
myMap["Feb"] = false
myMap["Mar"] = true

After doing some operation on this map, I want to delete it. I don't want to use for loop to iterate through each key and delete.

If I do re-initialize myMap again (like following), does it de-references the original and subject to garbage collection?

myMap = make(map[string]bool)
  • 写回答

1条回答 默认 最新

  • dousu1900 2018-05-14 05:17
    关注

    Golang FAQ on garbage collection:

    Each variable in Go exists as long as there are references to it. If the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors.

    In case there are no references used for the current map it will be garbage collected by the language. But for deleting a map There is no process other than looping over it and delete the keys one by one. as

    myMap := make(map[string]bool)
    for k, _ := range myMap{
        delete(myMap, k)
    }
    

    If you re-initialze the map using make it will not going to de-reference the same it will clear the map but will not dereference it. If you check for its len it will become zero

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        myMap := make(map[string]bool)
    
        myMap["Jan"] = true
        myMap["Feb"] = false
        myMap["Mar"] = true
        fmt.Println(len(myMap))
        myMap = make(map[string]bool)
        fmt.Println(len(myMap))
    
    }
    

    Along with that if you prints the address it points to same address.

    fmt.Printf("address: %p 
    ", &myMap)
    myMap = make(map[string]bool)
    fmt.Printf("address: %p ", &myMap)
    

    Playground Example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行