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
+11.7k Golang : Convert(cast) bigint to string
+6.7k Golang : Calculate pivot points for a cross
+7.4k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+25.1k Golang : Generate MD5 checksum of a file
+27.2k Golang : Convert CSV data to JSON format and save to file
+11.9k Golang : Detect user location with HTML5 geo-location
+10.9k Golang : Read until certain character to break for loop
+11k Golang : Calculate Relative Strength Index(RSI) example
+5.2k Golang : Return multiple values from function
+4.9k Golang : Display packages names during compilation
+19.9k Golang : Determine if directory is empty with os.File.Readdir() function
+7.3k Golang : Rot13 and Rot5 algorithms example