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 Golang : cannot assign type int to value (type uint8) in range error
+8.8k Golang : How to check if your program is running in a terminal
+6.7k Golang : Go as a script or running go with shebang/hashbang style
+6.1k Golang : HTTP Server Example
+32.7k Golang : UDP client server read write example
+17.7k Golang : Get ASCII code from a key press(cross-platform) example
+29.3k Golang : How do I convert int to uint8?
+6.3k Golang : Qt get screen resolution and display on center example
+6.1k Golang : Scramble and unscramble text message by randomly replacing words
+3.6k Golang : Display advertisement images or strings on random order
+6.4k Golang : Use regular expression to get all upper case or lower case characters example