Use len(slice) == 0 expression to check if a slice is empty or nil in Golang. The len() function returns the length of a slice, and an empty slice returns 0 length.

package main import ( "fmt" ) func main() { // Initialize an empty slice var numbers []int // Check if the slice is empty using len() if len(numbers) == 0 { fmt.Println("The slice is empty") } else { fmt.Println("The slice is not empty") } } // Output: The slice is empty
The nil slice is empty, but it is different from an initialized slice. It does not matter if a slice is nil or has zero length (initialized empty slice) because, in both cases, its length is 0.
The len() function abstracts away the distinction between nil and empty.
package main import ( "fmt" ) func main() { var s1 []int // nil slice s2 := []int{} // empty slice fmt.Println(len(s1), len(s2)) // Output: 0 0 fmt.Println(s1 == nil, s2 == nil) // Output: true false }
The above code shows that nil slice and initialized empty slice have length zero, representing two different objects.
By checking if a slice is empty, you can write safer and more efficient Go programs.
Check for Nil (If Explicitly Required)
If you are checking for an uninitialized slice (nil slice), you can use the if slice == nil expression.
package main func main() { var s1 []int // nil slice if s1 == nil { print("slice is nil") } else { print("slice is not nil") } } // Output: slice is nil
For better memory performance, it is always a good idea to create nil slices, which consume no memory, whereas empty slices have a non-nil header.
Don’t use the slice == nil approach to check emptiness because it misses non-nil empty slices.
When you try to loop over a nil or empty slice, it will not execute. That means, in that case, you don’t need to check len(slice) == 0 before looping.