skip to content
Alvin Lucillo

Clear slices and maps

/ 1 min read

Did you know that you can clear a map or slice with clear builtin function? Clearing them means they’re set to their zero values.

func main() {
	x := map[string]int{
		"1": 1,
		"2": 2,
	}
	fmt.Println(x)
	clear(x)
	fmt.Println(x)
	y := []int{1, 2, 3}
	fmt.Println(y)
	clear(y)
	fmt.Println(y)
}

Output

map[1:1 2:2]
map[]
[1 2 3]
[0 0 0]