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
+7.1k Golang : Null and nil value
+7.3k Golang : Scanf function weird error in Windows
+9.5k Golang : Read file with ioutil
+10.6k Golang : Flip coin example
+13.3k Golang : Linear algebra and matrix calculation example
+8.3k Useful methods to access blocked websites
+16.3k Golang :Trim white spaces from a string
+14.5k Golang : Execute function at intervals or after some delay
+8.1k Golang : Reverse text lines or flip line order example
+5.5k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+5.4k How to check with curl if my website or the asset is gzipped ?
+8k Golang : Handle Palindrome string with case sensitivity and unicode