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.5k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+10.4k Golang : Convert file content to Hex
+8.5k Golang : Implementing class(object-oriented programming style)
+8k Golang : Example of how to detect which type of script a word belongs to
+20k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+22.4k Golang : How to run Golang application such as web server in the background or as daemon?
+21.9k Golang : How to reverse slice or array elements order
+18.3k Golang : Convert IPv4 address to decimal number(base 10) or integer
+9.6k Golang : Generate EAN barcode
+6.6k CodeIgniter : form input set_value cause " to become & quot
+8.2k Golang : Trim everything onward after a word
+14.5k Golang : Recombine chunked files example