FlagSets facilitate the definition of separate sets of flags, providing support for implementing subcommands in a command-line interface.
In Go, you can create multiple FlagSet types and initialize the flag variables. However, when parsing these flag sets, you will encounter errors if the command line contains flags intended for another set.
f1 := flag.NewFlagSet("f1", flag.ContinueOnError) apply := f1.Bool("apply", false, "") silent := f1.Bool("silent", false, "") f2 := flag.NewFlagSet("f2", flag.ContinueOnError) reset := f2.Bool("reset", false, "")
To separate these FlagSets, distinguish between subcommands and subsequently invoke Parse on the appropriate set.
switch os.Args[1] { case "apply": f1.Parse(os.Args[2:]) fmt.Println("apply", *silent) case "reset": f2.Parse(os.Args[2:]) fmt.Println("reset", *loud) }
By adhering to this approach, you can define and parse independent FlagSets in GoLang, ensuring that flags are only applicable to their intended subcommands.
The above is the detailed content of How to Define and Parse Independent FlagSets in Go for Subcommands?. For more information, please follow other related articles on the PHP Chinese website!