How do I check for an empty slice?

GoSlice

Go Problem Overview


I am calling a function that returns an empty array if there are no values.

When I do this it doesn't work:

if r == [] {
    fmt.Println("No return value")            
}

The work around I'm using is:

var a [0]int
if r == a {
    fmt.Println("No return value")            
}

But declaring a variable just to check the return value doesn't seem right. What's the better way to do this?

Go Solutions


Solution 1 - Go

len() returns the number of elements in a slice or array.

Assuming whatever() is the function you invoke, you can do something like:

r := whatever()
if len(r) > 0 {
  // do what you want
}

or if you don't need the items

if len(whatever()) > 0 {
  // do what you want
}

Solution 2 - Go

You can just use the len function.

if len(r) == 0 {
    fmt.Println("No return value")            
}

Although since you are using arrays, an array of type [0]int (an array of int with size 0) is different than [n]int (n array of int with size n) and are not compatible with each other.

If you have a function that returns arrays with different lengths, consider using slices, because function can only be declared with an array return type having a specific length (e.g. func f() [n]int, n is a constant) and that array will have n values in it (they'll be zeroed) even if the function never writes anything to that array.

Solution 3 - Go

You can use the inbuilt function provided by Golang

> len()

It will helps you to easily find a slice is empty or not.

if len( yourFunction() ) == 0 {
    // It implies that your array is empty.
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKshitiz SharmaView Question on Stackoverflow
Solution 1 - GoSimone CarlettiView Answer on Stackoverflow
Solution 2 - GoabhinkView Answer on Stackoverflow
Solution 3 - GoASHWIN RAJEEVView Answer on Stackoverflow