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
+17.8k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+5.9k Golang : Decode XML data from RSS feed
+13.6k Golang : Find commonalities in two slices or arrays example
+3.8k Facebook : How to place save to Facebook button on your website
+18.4k Golang : Determine if directory is empty with os.File.Readdir() function
+8.3k Random number generation with crypto/rand in Go
+4.5k Golang : Detect words using using consecutive letters in a given string
+21.3k Generate checksum for a file in Go
+12.9k Android Studio : Use image as AlertDialog title with custom layout example
+7.7k Golang : Executing and evaluating nested loop in html template
+5.2k Javascript : Get operating system and browser information
+7.4k Golang : How to check variable or object type during runtime?