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 Python : Print unicode escape characters and string
+5.1k Golang : Pad file extension automagically
+13.5k Golang : unknown escape sequence error
+26k Golang : Convert(cast) string to uint8 type and back to string
+12.8k Golang : Handle or parse date string with Z suffix(RFC3339) example
+5.1k Swift : Convert string array to array example
+20.8k Golang : Get password from console input without echo or masked
+9.4k Golang : Validate IPv6 example
+5.6k Golang : Launching your executable inside a console under Linux
+11.3k Golang : Handle API query by curl with Gorilla Queries example
+12.8k Golang : List objects in AWS S3 bucket