How to Remove All Elements from an Array in Go

Here are two ways to remove or clear all the elements from an array in Go:

  1. Set the elements of an array equal to nil
  2. 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

Initialize an Array in Go

Check If the Array is Empty in Go

Constant Array in Go

Append an array to an array in Go