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
+1.3k Golang : A program that contain another program and executes it during run-time
+4.3k Golang : Identifying Golang HTTP client request
+4.5k Golang : How to get ECDSA curve and parameters data?
+2.5k nginx : force all pages to be SSL
+13.2k Golang : Delete duplicate items from a slice/array
+2.7k Golang : Example of custom handler for Gorilla's Path usage.
+5.5k Golang : Find commonalities in two slices or arrays example
+8.1k Curl usage examples with Golang
+3.8k Golang : Error reading timestamp with GORM or SQL driver
+41.1k Golang : Upload file from web browser to server
+5.2k Golang : flag provided but not defined error
+12.3k nginx: [emerg] unknown directive "passenger_enabled"