Clear
The built-in function clear takes an argument of map, slice, or type parameter type, and deletes or zeroes out all elements [[Go 1.21(https://go.dev/ref/spec#Go_1.21)]].
Call Argument type Result clear(m) map[K]T deletes all entries, resulting in an empty map (len(m) == 0) clear(s) []T sets all elements up to the length of s to the zero value of T clear(t) type parameter see below
clear
is a relatively recent addition to Go, added just over a year ago. And it’s a bit of a funny one, in my personal opinion.
The use with maps makes perfect sense to me.
Do you want to delete everything from an existing map, without creating a new one? clear
does that! Yay! It’s not a frequent requirement, but it’s nice that it exists, because there was no good alternative.
m := map[int]int{1: 1, 2: 2, 3: 3}
fmt.Println(m, len(m)) // map[1:1 2:2 3:3] 3
clear(m)
fmt.Println(m, len(m)) // map[] 0
The weird thing about clear
is that its behavior on slices is not very analogous, at least not to my way of thinking. When operating on a slice, clear
just zeros out the values.
s := []int{1, 2, 3, 4, 5}
fmt.Println(s, len(s), cap(s)) // [1 2 3 4 5] 5 5
clear(s)
fmt.Println(s, len(s), cap(s)) // [0 0 0 0 0] 5 5
I suppose the reason for this is that you can accomplish “deleting” everything in a slice very easily without clear
:
s := []int{1, 2, 3, 4, 5}
fmt.Println(s, len(s), cap(s)) // [1 2 3 4 5] 5 5
s = s[:0]
fmt.Println(s, len(s), cap(s)) // [] 0 5
If the type of the argument to
clear
is a type parameter, all types in its type set must be maps or slices, andclear
performs the operation corresponding to the actual type argument.If the map or slice is
nil
, clear is a no-op.
I’m also unsure why clear
doesn’t work on arrays directly. It’s easy enough to work around, though, if you want to:
a := [...]int{1, 2, 3, 4, 5}
fmt.Println(a, len(a), cap(a)) // [1 2 3 4 5] 5 5
// clear(a) // invalid argument: cannot clear a (variable of type [5]int)
clear(a[:])
fmt.Println(a, len(a), cap(a)) // [0 0 0 0 0] 5 5
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)