How to Check If Array is Empty in Golang

To check if an array is empty in Go, use the “len() function and compare its length to zero.” 

Example

package main

import "fmt"

func main() {
  emptySlice := []int{}
  nonEmptySlice := []int{1, 2, 3, 4, 5}

  if len(emptySlice) == 0 {
    fmt.Println("The slice is empty.")
  } else {
    fmt.Println("The slice is not empty.")
  }

 if len(nonEmptySlice) == 0 {
   fmt.Println("The slice is empty.")
 } else {
   fmt.Println("The slice is not empty.")
 }
}

Output

The slice is empty.
The slice is not empty.

In this example, we created two slices: an empty one and a non-empty one.

In the next step, we used the len() function to get the length of each slice and compare it to zero. If the length is zero, the slice is empty; otherwise, it’s not empty.

Note that you should not use if slice == nil to check if a slice is empty. This is because a non-nil slice with a length of zero (e.g., make([]int, 0)) is still considered empty.

Using len(slice) == 0 is the correct way to check for an empty slice, as it covers both nil and non-nil slices with zero length.

That’s it!

1 thought on “How to Check If Array is Empty in Golang”

  1. I have a question: what about an array of strings? (Or an array of an array of something else).

    Suppose I have a parameter being passed to a function, named myArray and its type is []string. Now I need to check if that array has nothing in it (an empty string counts as a valid entry!), because, otherwise, the call to, say, myString := myArray[0] will panic.

    In that case, would it make sense to use the following test:

    if len(myArray) != 0 {
    myString := myArray[0]
    } else {
    panic()
    }

    … or would that panic as well during the comparison call?

Comments are closed.