How do I check for an empty slice?
GoSliceGo 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.
}