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
+6.4k Golang : Command line ticker to show work in progress
+35.5k Upload multiple files with Go
+21.9k Golang : Fix type interface{} has no field or no methods and type assertions example
+7.8k Golang : Build and compile multiple source files
+13.3k Golang : Normalize unicode strings for comparison purpose
+23.7k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+16.3k How to enable MariaDB/MySQL logs ?
+6.3k Golang : Lock executable to a specific machine with unique hash of the machine
+9.6k Golang : Command line file upload program to server example
+4.2k Responsive Google Adsense