The Go documentation states that the FlagSet type allows the creation of independent sets of flags, which is useful for implementing subcommands in a command-line interface. However, implementing this functionality can be challenging.
When defining two FlagSets, parsing one of them may result in errors or warnings if the command line contains flags intended for the second FlagSet. For instance, consider the following code:
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) }
Executing cmd -apply or cmd -reset generates various warnings. This behavior is due to the lack of differentiation between subcommands. To separate these FlagSets effectively, it is necessary to distinguish the subcommands first and then parse the correct FlagSet.
An example of how to achieve this:
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) } }
This code allows the -silent flag to be used exclusively with the apply subcommand and the -loud flag to be used exclusively with the reset subcommand.
The above is the detailed content of How to Properly Define and Parse Independent FlagSets in Go for Subcommands?. For more information, please follow other related articles on the PHP Chinese website!