How to check if a slice is empty in Golang

#golang

Last updated on Jul 31, 2021 by Suraj Sharma



In this tutorial, you will learn how you can check if a slice is empty in Golang.



Check if a slice is empty


We can use the len() function to get the length of the slice in Golang.

Length of an empty slice is always 0


Example


import "fmt"

func main() {

    cities := make([]string, 0)
    if len(cities) == 0 {
        fmt.Println("The given slice is empty")
    }

    cities = append(cities, "New York")
    if len(cities) > 0 {
        fmt.Printf("The length of the slice is: %d", len(cities))
    }
}


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.