How to Check If Array is Empty in Golang

To check if an array is empty in Go, you can use the “len()” function. In Golang, arrays have a fixed size, so they cannot be empty. However, if you’re working with slices with a variable length, you can check if a slice is empty by comparing its length to zero using the “len()” function.

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.

Leave a Comment