Independent Flag Sets in GoLang
The Go documentation for the flag package states that it allows for the definition of independent sets of flags, suitable for implementing subcommands in a command-line interface. However, the question arises as to how to achieve this functionality.
In a scenario where two FlagSet objects are defined, parsing one may result in errors and warnings if the command line contains flags intended for the other. The following example illustrates this issue:
f1 := flag.NewFlagSet("f1", flag.ContinueOnError) apply := f1.Bool("apply", false, "") silent := f1.Bool("silent", false, "") if err := f1.Parse(os.Args[1:]); err == nil { fmt.Println(*apply, *silent) } f2 := flag.NewFlagSet("f2", flag.ContinueOnError) reset := f2.Bool("reset", false, "") if err := f2.Parse(os.Args[1:]); err == nil { fmt.Println(*reset) }
This code produces warnings when trying to execute cmd -apply or cmd -reset. The goal is to maintain separate FlagSet objects, ensuring that -silent only works for -apply.
The solution lies in distinguishing the subcommands and then calling Parse on the appropriate FlagSet. The revised code:
f1 := flag.NewFlagSet("f1", flag.ContinueOnError) silent := f1.Bool("silent", false, "") f2 := flag.NewFlagSet("f2", flag.ContinueOnError) loud := f2.Bool("loud", false, "") switch os.Args[1] { case "apply": if err := f1.Parse(os.Args[2:]); err == nil { fmt.Println("apply", *silent) } case "reset": if err := f2.Parse(os.Args[2:]); err == nil { fmt.Println("reset", *loud) } }
With this approach, only the relevant FlagSet will be parsed based on the specified subcommand, ensuring the desired behavior.
The above is the detailed content of How to Implement Independent Flag Sets for Subcommands in Go?. For more information, please follow other related articles on the PHP Chinese website!