Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Built-in Functions

Go clear() function

Reference for Go clear() (Go 1.21+): remove all entries from a map or set every slice element to its zero value, with length and capacity behavior.

clear was added in Go 1.21. On a map it deletes every entry, leaving an empty map. On a slice it sets every element, up to the slice's length, to the zero value of the element type. It never changes the length or the capacity.

It accepts maps, slices and, in generic code, type parameters whose type set contains only maps and slices. It does not work on arrays, strings or channels.

Go
clear(m) // len(m) == 0
clear(s) // all elements are zero values, len(s) unchanged

Try it

Go Clearing a map and a slice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Zeroing pointers before shrinking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func clear[T ~[]Type | ~map[Key]Type](t T)
Argument Effect
Map Removes all entries.
Slice Sets elements s[0:len(s)] to their zero values. Elements beyond the length (up to the capacity) are not touched.
nil map or slice No-op.

Returns: nothing.

Usage notes

  • Reuse versus new map. clear(m) keeps the allocated buckets, which saves allocations when you refill the map. If the map grew very large once, a fresh make can release memory.
  • Length stays. To empty a slice, use s = s[:0]; this keeps old values in the array. clear(s) zeroes them but does not shorten.
  • Garbage collection. Zeroing pointer elements helps the collector free what they pointed to, which matters for long-lived slices used as queues or stacks.
  • NaN keys. clear removes NaN keys from a map, which delete(m, math.NaN()) cannot do.
  • Not for arrays. To zero an array, assign the zero value: arr = [5]int{}. To zero a slice of an array use clear(arr[:]).
  • Concurrency. Like other map writes, clear must not race with other access to the map.
  • Older Go versions. Before 1.21, loop with delete (the compiler turned that into an efficient clear) or use a for i := range s { s[i] = zero } loop.