Search code examples
gogarbage-collectiongo-map

golang de-reference a map


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)

Solution

  • 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 \n", &myMap)
    myMap = make(map[string]bool)
    fmt.Printf("address: %p ", &myMap)
    

    Playground Example