Golang : Variadic function arguments sanity check example
Problem:
Golang is cool and you love to use variadic function frequently. You have a variadic function such as a totalizer functions that accept any number of arguments. Such as
func variadicFunction(arguments ...int) {}
Somehow a user of your program or variadic function managed to sneak in a null/nil or empty argument. This caused your variadic function to go crazy.
How to prevent this from happening?
Solution:
You want to perform sanity check on your users and their input arguments first before processing further. For example :
package main
import "fmt"
func totalizer(values ...int) {
if values == nil {
fmt.Println("boom! - no number in arguments")
//panic("kaboom") -- if you choose to kill the program
} else {
fmt.Print(values, " ")
total := 0
for _, value := range values {
total += value
}
fmt.Println(total)
}
}
func main() {
totalizer(2)
totalizer(1, 2, 3)
totalizer()
}
Output:
[2] 2
[1 2 3] 6
boom! - no values given in arguments
Happy coding and don't let your user bomb your program!
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
+9.7k Golang : Sieve of Eratosthenes algorithm
+6.8k Golang : Scan files for certain pattern and rename part of the files
+8.8k Golang : Check if user agent is a robot or crawler example
+5.6k Golang : Totalize or add-up an array or slice example
+10.1k CodeIgniter : How to check if a session exist in PHP?
+7.7k Golang : Random integer with rand.Seed() within a given range
+19.5k Golang : Clean up null characters from input data
+30.9k Golang : Convert []string to []byte examples
+6.8k Golang : Check from web if Go application is running or not
+18.8k nginx: [emerg] unknown directive "passenger_enabled"
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+6.9k Golang : Configure Apache and NGINX to access your Go service example