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.4k Golang : Read data from config file and assign to variables
+21.8k Golang : How to run Golang application such as web server in the background or as daemon?
+7k Golang : How to iterate a slice without using for loop?
+26.4k Golang : How to check if a connection to database is still alive ?
+12k Golang : How to check if a string starts or ends with certain characters or words?
+5k Golang : Print instead of building pyramids
+9.1k Golang : Web(Javascript) to server-side websocket example
+42.7k Golang : Convert []byte to image
+22.5k Golang : simulate tail -f or read last line from log file example
+10.8k Golang : Read until certain character to break for loop
+7.9k Golang : Randomize letters from a string example
+16.5k Golang : read gzipped http response