The clear()
function is built into the Go language, and it zeroes out all elements of a slice, or eliminates all entries from a map. It is separate from the delete()
function.
When used on a slice, clear()
does not resize the underlying memory—it just assigns zero to all elements. And for maps, clear()
is like calling delete()
on all keys.
This Go program uses the clear()
built-in on both a slice and a map. On the map, it also uses the delete function. It prints the resulting elements after calling clear.
int
slice we create with a slice expression. It is possible to use make()
to create a slice here.string
keys and int
values—it has 3 of each.clear()
on a map, the entire map is erased and we are left with an empty map.package main import "fmt" func main() { // Part 1: create an int slice. values := []int{10, 20, 30} fmt.Println("Before clear:", values) // Part 2: use clear on the int slice. clear(values) fmt.Println("After clear: ", values) // Part 3: create a map with 3 keys and 3 values. lookup := map[string]int{"bird": 10, "frog": 20, "rabbit": 30} fmt.Println("Map: ", lookup) // Part 4: use delete to remove a key and its associated value from the map. delete(lookup, "bird") fmt.Println("After delete:", lookup) // Part 5: use clear to empty the map. clear(lookup) fmt.Println("After clear: ", lookup) }Before clear: [10 20 30] After clear: [0 0 0] Map: map[bird:10 frog:20 rabbit:30] After delete: map[frog:20 rabbit:30] After clear: map[]
string
sliceWhat happens when we clear a slice of strings? While ints are replaced with a 0 value, we get empty strings when we are using strings.
string
literal, but are not nil
—there is a difference.package main import "fmt" func main() { values := []string{"cat", "dog", "bird"} clear(values) // We have an empty string after calling clear on a string slice. for _, v := range values { if v == "" { fmt.Println("Empty") } } }Empty Empty Empty
Though clear()
is not available in early versions of the Go language, it is a useful feature in newer releases. It is separate from the delete()
built-in.
Clear replaces values with 0 or the empty string
literal, and is different than the delete built-in. Delete
, meanwhile, is used on maps and removes a key-value pair.