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
+4.8k PHP : Extract part of a string starting from the middle
+21.2k Golang : Convert(cast) string to rune and back to string example
+10.6k Golang : Get local time and equivalent time in different time zone
+20.6k Nginx + FastCGI + Go Setup.
+22.7k Golang : Round float to precision example
+5.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+7.4k Golang : Scanf function weird error in Windows
+22.5k Golang : Convert Unix timestamp to UTC timestamp
+13.7k Golang : Activate web camera and broadcast out base64 encoded images
+12.7k Android Studio : Highlight ImageButton when pressed on example
+14.5k Golang : Find network of an IP address
+9.1k Golang : Simple histogram example