I want my function to take optional arguments in an efficent way.
Reading similar posts led me to variadic args and I'm trying to implement it alongside the flag package (simply looking for any alternative to the users being able to run available command line flags of their choice.. This is my flag package usage:
func main() {
var target string
var method string
flag.StringVar(&target, "target", "http://google.com/robots.txt", "Target address")
flag.StringVar(&method, "method", "GET", "Method")
flag.Parse()
requests.MakeRequest(target, method)
}
This is an example of variadic args function:
func foo(params ...int) {
fmt.Println(len(params))
}
func main() {
foo()
foo(1)
foo(1, 2, 3)
}
Can I combine the two? If this is not possible - how can I pass main program's user given arguments to a variadic function then?
Your question shows a misunderstanding, what variadic arguments are for.
As you realized, variadics are used, when the amount of arguments to a function varies. You try to use this concept to hand over parsed commandline arguments of a variable amount. This is a bad idea in many ways. The obvious here is, that you are coupling your commandline arguments with the distribution of the flags and arguments in your code. Another is, that the variadic arguments loose the positional information. How do you expect to identify which 4 of the 5 arguments you have received?
You should define a struct to hold the flags for your code and write a commandline parser, that fills or creates this struct from defaults and given commandline options. This struct is then used to provide the flags and options throughout your application.
In practice, this could look like this:
type options struct {
target string
method string
}
func main() {
config := parseCommandLine()
theRealStuffHappensHere(config)
}
func theRealStuffHappensHere(config options) {
if config.method == "GET" {
// ...
}
}
func parseCommandLine() options {
var config options
flag.StringVar(&(config.target), "target", "http://google.com/robotstxt", "Target address")
flag.StringVar(&(config.method), "method", "GET", "Method")
flag.Parse()
return config
}
The variadic arguments are heavily used in the fmt
package, where the amount of required arguments depends on the amount of placeholders in the format string. Your usecase does not match.