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
+9.9k Golang : Function wrapper that takes arguments and return result example
+7.2k Golang : Array mapping with Interface
+23.2k Golang : Print out struct values in string format
+5.2k Python : Create Whois client or function example
+52.7k Golang : How to get struct field and value by name
+5.1k Golang : Display packages names during compilation
+9.4k Golang : How to get username from email address
+41.5k Golang : Convert string to array/slice
+10k Golang : Channels and buffered channels examples
+7.9k Golang : Regular Expression find string example
+4.1k Detect if Google Analytics and Developer Media are loaded properly or not
+5.7k Swift : Get substring with rangeOfString() function example