Home > Backend Development > Golang > How to Define and Parse Independent FlagSets in Go for Subcommands?

How to Define and Parse Independent FlagSets in Go for Subcommands?

Linda Hamilton
Release: 2024-12-28 10:59:31
Original
421 people have browsed it

How to Define and Parse Independent FlagSets in Go for Subcommands?

Defining Independent FlagSets in GoLang

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, "")
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template