How to Clear a Slice or Map in Go Using the `clear` Built-In Function
Go 1.21 introduced the clear built-in function as the idiomatic way to delete all entries from a map or zero-out slice elements while preserving length and capacity.
The clear built-in provides a concise, readable alternative to manual iteration when you need to reset collections. According to the JetBrains/go-modern-guidelines repository, this function represents current Go best practices for collection management.
Understanding the clear Built-In in Go
Go 1.21 added clear to the language specification as a universal cleanup mechanism for maps and slices. The implementation handles each type differently while maintaining consistent syntax.
Clearing Maps with clear()
For maps, clear(m) iterates internally and deletes every key-value pair. This produces the same result as manually looping with delete(), but expresses intent more clearly and requires no boilerplate code.
// Clearing a map completely
m := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
clear(m) // m is now empty (len == 0)
The guideline definition in internal/guidelines/guidelines.json explicitly recommends: "Use clear(m) to delete all map entries or clear(s) to zero slice elements" (see lines 721-735).
Zeroing Slices with clear()
For slices, clear(s) sets every element to the zero value of the element type. Unlike re-slicing to zero length (s = s[:0]), this operation preserves the original length and capacity while clearing the data.
// Zero-ing a slice (preserves length & capacity)
s := []int{5, 6, 7}
clear(s) // s == []int{0, 0, 0}, len(s) == 3, cap(s) unchanged
This distinction matters when you need to reuse the underlying array without reallocating memory, but want to ensure no stale data remains accessible through the slice header.
Implementation in the Go Modern Guidelines Repository
The JetBrains/go-modern-guidelines project documents this pattern in its structured guideline definitions. The JSON specification resides in internal/guidelines/guidelines.json, which contains the formal definition including usage examples and rationale.
The CLI tool that presents these guidelines loads this data at runtime through internal/guidelines/guidelines.go (lines 21-27). This architecture separates the static rule definitions from the presentation layer, allowing the repository to serve both as documentation and as a functional command-line reference tool.
Summary
- Go 1.21 requirement: The
clearbuilt-in requires Go version 1.21 or later. - Map behavior:
clear(m)deletes all keys, equivalent tofor k := range m { delete(m, k) }but more concise. - Slice behavior:
clear(s)zeroes elements while preserving length and capacity, unlikes = s[:0]which truncates length. - Source reference: The official guideline lives in
internal/guidelines/guidelines.jsonwithin the JetBrains repository.
Frequently Asked Questions
What is the difference between clear(s) and s = s[:0] for slices?
clear(s) sets every element to its zero value while keeping the slice length intact, whereas s = s[:0] creates a zero-length slice that still references the same underlying array. Use clear() when you need to zero-out data for security or reuse, and use re-slicing when you simply want to reset the length for appending new elements.
Does clear() free memory for maps or slices?
No, clear() does not release backing memory. For maps, it removes all entries but keeps the bucket structure allocated for future use. For slices, it only zeroes values in place. To actually release memory, you must set the variable to nil or allow it to go out of scope.
Can I use clear() on nil maps or slices?
Yes, clear() handles nil collections safely. Calling clear(nil) or clear(nilMap) is a valid no-op that does not panic, making it safe to use defensively without nil checks.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →