Clearing map[string]int

What are ways of clearing map keys and values?

for k := range m {
    delete(m, k)

Is there shorter or another way without using for?

Go is not designed for Code Golf.

As always, use simple, idiomatic code forms to give the compiler and runtime the best opportunities for optimization.

Go is open source. Check the source code.

commit aee71dd70b3779c66950ce6a952deca13d48e55e

cmd/compile: optimize map-clearing range idiom

replace map clears of the form:

        for k := range m {
                delete(m, k)

(where m is map with key type that is reflexive for ==)
with a new runtime function that clears the maps backing
array with a memclr and reinitializes the hmap struct.

You are using the optimal form.

if you want to delete all the values, you could reallocate the map

package main

import (

func main() {

	a := make(map[string]string)
	a["apple"] = "a"
	a["banana"] = "b"

	fmt.Println("before ", a)
	a = make(map[string]string)
	fmt.Println("after ", a)

I believe the garbage collector would reclaim the memory

1 Like

I use this “allocate a fresh map” tactic extensively in production services.
Yes, GC’ed.

Thank you!