How to Clear a Map in Golang

To clear a map in Golang, you can either “reinitialize the map with make() function” or “for loop with delete() function.”

Method 1: Reinitialize the map with make()

Reinitializing the map with the make() function is more idiomatic and efficient in Go. If not referenced elsewhere, the old map will be collected by the garbage collector.

Reinitializing like this is generally faster than iterating through the map and deleting each entry, especially for larger maps.

Syntax

m = make(map[string]int)

Example

package main

import (
  "fmt"
)

func main() {
  m := map[string]int{
    "A": 1,
    "B": 2,
    "C": 3,
  }

  fmt.Println("Before clearing:", m)

  m = make(map[string]int)

  fmt.Println("After clearing:", m)
}

Output

Clear a Map in Golang

This will point “m” to a new empty map; if there are no other references to the old map, the garbage collector will clean it up eventually.

Method 2: for loop with delete() function

To clear all the entries from a map in Go, you can use a “for loop.”

Example

package main

import (
  "fmt"
)

func main() {
  m := map[string]int{
    "A": 1,
    "B": 2,
    "C": 3,
  }

  fmt.Println("Before clearing:", m)

  // Clearing the map
  for k := range m {
    delete(m, k)
  }

  fmt.Println("After clearing:", m)
}

Output

Before clearing: map[A:1 B:2 C:3]

After clearing: map[]

The key function here is delete(), which removes the key-value pair associated with the given key from the map. Looping over the map and deleting every key effectively clears the map.

There are scenarios where you might want to clear the existing map. This is especially true when multiple parts of the code reference the same map. In such cases, clearing the map in-place ensures that all references see the cleared state.

That’s it!

Related posts

Delete a Key from a Map in Go

How to Merge Maps in Go

How to Declare a Constant Map in Go

Leave a Comment