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
+29.5k Golang : Login(Authenticate) with Facebook example
+10.2k Golang : Bcrypting password
+18.8k Golang : Implement getters and setters
+23.6k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+6.1k nginx : force all pages to be SSL
+10.3k Golang : Detect number of faces or vehicles in a photo
+11.1k Golang : Create S3 bucket with official aws-sdk-go package
+41k Golang : How to check if a string contains another sub-string?
+6.9k Golang : Muxing with Martini example
+11.3k Golang : Byte format example
+35.3k Golang : Strip slashes from string example
+19.9k Golang : Measure http.Get() execution time