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
+2.7k Javascript : How to replace HTML inside <div>?
+3.9k Golang Hello World Example
+9.9k Golang : convert rune to integer value
+15.7k Golang : Get current file path of a file or executable
+6.1k Golang : convert rune to unicode hexadecimal value and back to rune character
+2.9k Golang : Get final or effective URL with Request.URL example
+4.9k Golang : Replace a parameter's value inside a configuration file example
+4k Golang : Underscore string example
+3k Golang : Build and compile multiple source files
+16.5k Golang : Regular Expression for alphanumeric and underscore
+2.4k Golang : Issue HTTP commands to server and port example
+2.7k Unix/Linux : How to test user agents blocked successfully ?