Golang : How to check if slice or array is empty?
Problem :
One of your code is throwing out panic error and apparently it is trying to do a for loop on an empty slice or array.
Solution :
Check if the slice or array is empty first with the builtin len()
function, such as len(slice) <= 0
. If the slice or array is empty, skip the for loop.
IF you are trying to check if your SQL query returns any rows. Such as from QueryRow()
function. Then check the returned error message.
For example :
err := db.QueryRow("SELECT ...").Scan(&id, &username)
if err == sql.ErrNoRows {
// do your stuff
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.3k Golang : Dealing with postal or zip code example
+3.7k Chrome : How to block socketloop.com links in Google SERP?
+8.7k Golang : Identifying Golang HTTP client request
+28.2k Golang : Login(Authenticate) with Facebook example
+5k Golang : Compound interest over time example
+7.9k Golang : Intercept and compare HTTP response code example
+3.5k Golang : Valued expressions and functions example
+81.4k Golang : How to convert character to ASCII and back
+13.2k Golang : Reset buffer example
+5.1k Golang : Debug with Godebug
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+3.9k Which content-type(MIME type) to use for JSON data