Command-Line Subcommands
This Go program demonstrates the use of subcommands with different sets of flags using the flag
package. It allows you to run the program with either a "foo" or "bar" subcommand, each having its own set of flags. Let's break down the code with inline comments:
Explanation:
Defining Flags for Subcommands:
The program defines two sets of flags using
flag.NewFlagSet
for the 'foo' and 'bar' subcommands.
Parsing Subcommands:
The program checks the number of command-line arguments. If there are not enough arguments, it prints an error message and exits.
Switching Between Subcommands:
The program uses a switch statement to determine whether the first argument is "foo" or "bar."
Parsing Subcommand-Specific Flags:
Depending on the subcommand, it parses the specific set of flags for that subcommand using
fooCmd.Parse
orbarCmd.Parse
.
Printing Results:
After parsing the subcommand-specific flags, the program prints the results.
You can run the program with commands like:
or
This allows you to have different flags for different subcommands.
Last updated
Was this helpful?