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
+19.1k Golang : Secure(TLS) connection between server and client
+9.8k Golang : Simple image viewer with Go-GTK
+5.6k Golang : Calculate diameter, circumference, area, sphere surface and volume
+22.1k Find and replace a character in a string in Go
+8.5k Golang : Qt get screen resolution and display on center example
+26.6k Get file path of temporary file in Go
+13.8k nginx: [emerg] unknown directive "ssl"
+7.6k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+8.8k Golang : Sort and reverse sort a slice of integers
+4.8k Fix fatal error: evacuation not done in time problem
+9.9k Golang : Web routing/multiplex example