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
+18.3k Golang : Generate thumbnails from images
+34.9k Golang : Integer is between a range
+6k Javascript : Generate random key with specific length
+7.2k Golang : Convert source code to assembly language
+20.9k Golang : How to get time zone and load different time zone?
+10.7k How to test Facebook App on localhost ?
+9.1k Golang : Create unique title slugs example
+4.9k Python : Create Whois client or function example
+18.8k Golang : Get host name or domain name from IP address
+20.4k PHP : Convert(cast) int to double/float
+8.3k Golang : Set or add headers for many or different handlers
+20.9k Golang : Convert(cast) string to rune and back to string example