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
+12k Golang : Convert decimal number(integer) to IPv4 address
+15.8k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+26.1k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+10.6k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+6.9k Default cipher that OpenSSL used to encrypt a PEM file
+3.4k Golang : Fix go-cron set time not working issue
+37.7k Golang : Comparing date or timestamp
+39.1k Golang : How to iterate over a []string(array)
+19.3k Golang : Populate dropdown with html/template example
+17.8k How to enable MariaDB/MySQL logs ?
+7.6k Golang : How to handle file size larger than available memory panic issue
+22.7k Golang : Strings to lowercase and uppercase example