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