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
+5.3k JavaScript/JQuery : Redirect page examples
+6.2k Golang : Scan forex opportunities by Bollinger bands
+18.9k Golang : Delete duplicate items from a slice/array
+8.9k Yum Error: no such table: packages
+9.4k Golang : Generate random Chinese, Japanese, Korean and other runes
+20.5k Golang : Determine if directory is empty with os.File.Readdir() function
+9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+4.8k JavaScript: Add marker function on Google Map
+11.1k How to test Facebook App on localhost ?
+7.4k Golang : How to iterate a slice without using for loop?
+8.2k Golang : Variadic function arguments sanity check example
+6.8k Golang : Derive cryptographic key from passwords with Argon2