remove all keys and values from a map in go

To remove all the keys and values from a map in Go, we can loop over all the keys of the map using a for range loop and delete each key using the delete built-in function. Here's an example:

main.go
// create a sample map
m := map[string]int{
    "a": 1,
    "b": 2,
    "c": 3,
}

// loop over all keys and delete them
for k := range m {
    delete(m, k)
}

// print empty map
fmt.Println(m) // Output: map[]
211 chars
15 lines

Alternatively, we can also create a new empty map using the make built-in function, which will overwrite the old map with the new empty map:

main.go
// create a sample map
m := map[string]int{
    "a": 1,
    "b": 2,
    "c": 3,
}

// create new empty map
m = make(map[string]int)

// print empty map
fmt.Println(m) // Output: map[]
184 chars
13 lines

In both cases, we end up with an empty map with no keys or values.

related categories

gistlibby LogSnag