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.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+4.7k Golang : Error handling methods
+8k Golang : How to check if a string with spaces in between is numeric?
+7.8k Golang : Write multiple lines or divide string into multiple lines
+13k Golang : How to determine if user agent is a mobile device example
+26.5k Get file path of temporary file in Go
+11.2k Golang : Listen and Serve on sub domain example
+8.6k Golang : How to check if a website is served via HTTPS
+5.7k Golang : Warp text string by number of characters or runes example
+4k Fix Google Analytics Redundant Hostnames problem
+8.7k Golang : Identifying Golang HTTP client request
+10.6k Golang : Convert(cast) float to int