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
+7k Fix sudo yum hang problem with no output or error messages
+14k Golang : convert(cast) string to float value
+17.1k Golang : Set up source IP address before making HTTP request
+8.3k How to show different content from website server when AdBlock is detected?
+16.5k Golang :Trim white spaces from a string
+7.7k Javascript : Push notifications to browser with Push.js
+9.6k Golang : Apply Histogram Equalization to color images
+9.8k Golang : Eroding and dilating image with OpenCV example
+9.3k Golang : Generate Codabar
+7.1k Golang : constant 20013 overflows byte error message
+5.6k PHP : Fix Call to undefined function curl_init() error
+10.3k Golang : Wait and sync.WaitGroup example