snippetgoCritical
How do I check for an empty slice?
Viewed 0 times
emptyhowslicecheckfor
Problem
I am calling a function that returns an empty array if there are no values.
When I do this it doesn't work:
The work around I'm using is:
But declaring a variable just to check the return value doesn't seem right. What's the better way to do this?
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?
Solution
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
}Code Snippets
r := whatever()
if len(r) > 0 {
// do what you want
}if len(whatever()) > 0 {
// do what you want
}Context
Stack Overflow Q#38144050, score: 180
Revisions (0)
No revisions yet.