Clear Builtin Resets Maps And Slices

Reset a map or slice in one builtin call: clear empties every map key and stores zero values while keeping slice length and capacity.

GoData Integrity

Code

gosnippet
24 lines
package main

import "fmt"

func main() {
	// the clear builtin resets a map: every key is deleted in one call
	counts := map[string]int{"orders": 3, "billing": 1, "auth": 9}
	clear(counts)
	fmt.Println("map len after clear:", len(counts))
	_, present := counts["orders"]
	fmt.Println("orders present:", present)

	// clear resets a slice: zero values fill every slot, len and cap stay
	buf := []int{7, 8, 9}
	clear(buf)
	fmt.Println("slice after clear:", buf, "len:", len(buf), "cap:", cap(buf))

	// on nil maps and nil slices clear is a no-op, no panic
	var nilSlice []int
	clear(nilSlice)
	var nilMap map[string]int
	clear(nilMap)
	fmt.Println("nil targets cleared without panic")
}

The file, statement by statement

Clear Builtin Resets Maps And Slices is built around the function main.

Applying it

Each phase of the run announces itself — map len after clear:, orders present:, slice after clear: — when the file runs.

Statements that matter

counts := map[string]int{"orders": 3, "billing": 1, "auth": 9}

Interactive Tools for This Topic

FAQ

What does Clear Builtin Resets Maps And Slices print when run?
The script runs standalone; its 4 labeled outputs include `map len after clear:`, `orders present:`, `slice after clear:`.