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
+10.9k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+13.2k Golang : Read from buffered reader until specific number of bytes
+9.8k Golang : Identifying Golang HTTP client request
+36.1k Golang : Convert date or time stamp from string to time.Time type
+7.9k Golang : Find relative luminance or color brightness
+11.2k Golang : Concatenate (combine) buffer data example
+12.4k Golang : Listen and Serve on sub domain example
+5.5k Unix/Linux/MacOSx : Get local IP address
+8.6k Golang : Take screen shot of browser with JQuery example
+21.9k Golang : Repeat a character by multiple of x factor
+18.3k Golang : Write file with io.WriteString