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.4k Golang : Derive cryptographic key from passwords with Argon2
+6.5k Golang : Reverse by word
+4.8k Swift : Convert (cast) Float to Int or Int32 value
+4.6k HTTP common errors and their meaning explained
+7.9k Golang : Get final or effective URL with Request.URL example
+13.2k Golang : Read XML elements data with xml.CharData example
+6.8k Golang : Takes a plural word and makes it singular
+7.1k Golang : alternative to os.Exit() function
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+11.4k Golang : Secure file deletion with wipe example
+21.8k Golang : Securing password with salt
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?