Here are two ways to remove or clear all the elements from an array in Go:
- Set the elements of an array equal to nil
- Clear all elements in an array using zero length
Method 1: Set the elements of an array equal to nil
If you are using slices, you can set them to nil or use slice = slice[:0] to clear all elements while reusing the underlying array. You can set all elements of an array to a zero value (e.g., 0 for integers, 0.0 for floats, “” for strings, nil for pointers, etc.) to effectively “clear” it.
Here is an example of an array:
package main
import (
"fmt"
)
func main() {
// An array of 3 integers
var arr []int
// use append function to store values
arr = append(arr, 2)
arr = append(arr, 3)
arr = append(arr, 4)
arr = append(arr, 8)
fmt.Println("Before clearing:", arr)
arr = nil
fmt.Println("After clearing:", arr)
}
Output
Before clearing: [2 3 4 8]
After clearing: []
Method 2: Clear all elements in an array using zero length
In Go, the length of an array is fixed when it’s declared, so you can’t change its length to 0 to clear it. Arrays in Go are not dynamically resizable like slices. Therefore, setting the length of an array to 0 isn’t applicable in Go.
However, if you are using a slice (which is built on top of an array and provides more flexibility), you can set its length to 0 to clear it:
package main
import (
"fmt"
)
func main() {
// An array of 3 integers
var arr []int
// Use append function to store values
arr = append(arr, 2)
arr = append(arr, 3)
arr = append(arr, 4)
arr = append(arr, 8)
fmt.Println("Before clearing:", arr)
// Slice with 0 length
arr = arr[:0]
fmt.Println("After clearing:", arr)
}
Output
Before clearing: [2 3 4 8]
After clearing: []
That’s it!
Related posts
Check If the Array is Empty in Go
Append an array to an array in Go

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.