Skip to content

Golang: Check If slice Is Empty

When you want to check if a slice is empty simply check the length of the slice with len() method:

func len(v Type) int

You can use len() on both nil and empty slices:

package main

import "fmt"

func main() {

	var nilSlice []string
	emptySlice := []string{}

	if len(emptySlice) == 0 {
		fmt.Println("Empty slice!")
	}

	if len(nilSlice) == 0 {
		fmt.Println("Empty slice!")
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *