If I have a function where the last argument is optional, is it an appropriate practice to use ... to allow the argument to be optional, or is it considered bad form?
Example:
func Foo(s ...string) {
switch len(s) {
case 0:
fmt.Println("You didn't pass an argument")
case 1:
fallthrough
default:
fmt.Printf("You passed %s\n", s[0])
}
}
Foo("bar") // "You passed bar"
Foo() // "You didn't pass an argument"
Foo("bar", "baz") // "You passed bar"
In this example, I don’t care if too many arguments were passed, but I could handle that in the default: case when needed.
I would not recommend this. There are different problems with (ab)using variadic parameters for passing optional arguments. Most important of them is probably that the form of the last
arg ...T)allows for only one type. For more than one optional parameter with more than one type one can use...interface{}but that incurs unnecessary run time (un)boxing costs and lacks any (usefull) compile time type checking.Another possible argument against is that I don’t think you’ll find an example/precedent for this anywhere in the standard library, which is considered an informal Go coding style guide by some.