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

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探