Clear Builtin Resets Slices And Maps

Reset a slice in place with the clear builtin, which zeroes elements while keeping length, and empty a map completely, replacing the manual zeroing loops.

GoData Integrity

Code

gosnippet
28 lines
package main

import "fmt"

func main() {
	scores := []int{91, 87, 99}
	// clear 作用在切片上:把所有元素置零,len 不变
	clear(scores)
	fmt.Println("cleared slice:", scores, "len", len(scores))

	quota := map[string]int{"api": 10, "web": 5}
	// clear 作用在 map 上:删光所有键
	clear(quota)
	fmt.Println("cleared map:", quota, "len", len(quota))

	// 复用前的等价老写法:切片逐元素置零、map 逐键 delete
	counts := []string{"a", "b", "c"}
	for i := range counts {
		counts[i] = ""
	}
	fmt.Printf("manual slice reset: %q\n", counts)

	sessions := map[string]string{"u1": "tok", "u2": "tok"}
	for k := range sessions {
		delete(sessions, k)
	}
	fmt.Println("manual map clear:", sessions)
}

What the code does

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

The loop for i := range counts is the only repeated construct.

Caveats

  • The import surface (if any) is all standard library, all versioned with the language itself.

Applying it

The demo output is labeled (cleared slice:, cleared map:, manual slice reset:), letting each printed line point back to the operation that emitted it.

Statements that carry the weight

for k := range sessions {
	delete(sessions, k)
}
for i := range counts {
	counts[i] = ""
}

Interactive Tools for This Topic

FAQ

What does Clear Builtin Resets Slices And Maps print when run?
Invoke the file as-is — the `cleared slice:`, `cleared map:`, `manual slice reset:` prefixes identify which step printed each line.