I see here at least two questions, maybe three.
- How do you declare a global variable?
- How do you declare a global constant?
- How do you parse command line options and arguments?
Hope the code below demonstrates this in a useful way. The flag pack was one of the first packets I had to cut my teeth in Go. At that time, this was not obvious, although the documentation is improving.
FYI, at the time of this writing, I am using http://weekly.golang.org as a reference. The main site is too outdated.
package main import ( "flag" "fmt" "os" ) //This is how you declare a global variable var someOption bool //This is how you declare a global constant const usageMsg string = "goprog [-someoption] args\n" func main() { flag.BoolVar(&someOption, "someOption", false, "Run with someOption") //Setting Usage will cause usage to be executed if options are provided //that were never defined, eg "goprog -someOption -foo" flag.Usage = usage flag.Parse() if someOption { fmt.Printf("someOption was set\n") } //If there are other required command line arguments, that are not //options, they will now be available to parse manually. flag does //not do this part for you. for _, v := range flag.Args() { fmt.Printf("%+v\n", v) } //Calling this program as "./goprog -someOption dog cat goldfish" //outputs //someOption was set //dog //cat //goldfish } func usage() { fmt.Printf(usageMsg) flag.PrintDefaults() os.Exit(1) }
source share