flag.FlagSet defines a named collection of command-line flags, their defaults, usage descriptions, and value parsers. Register flags with methods such as StringVar and IntVar, then call Parse to read arguments and update the variables linked through pointers. This replaces manual parsing, validation, and much of the associated error handling. section 4.3 section 4.3.1
Parse options into a configuration
Create a FlagSet with a program name and ContinueOnError when the caller should control failure handling. Register each option against a config field, then return Parse(args). For example, -n=25 updates an integer request-count field, while -url supplies a string field. ContinueOnError makes Parse return an error rather than ending the program, which keeps main responsible for exit status. section 4.3.1
Figure 4.5 FlagSet maps flag names to Flags. Its Parse method parses the flags from command-line arguments, and the value parsers update the variables.
A FlagSet maps each flag name to a Flag; parsing invokes the flag’s value parser and updates its associated variable. section 4.3
A FlagSet also generates usage output and reports parsing errors. Usage descriptions determine the generated flag listing, including types and defaults. Backticks around a placeholder in a usage description make that placeholder appear beside the flag name, such as -url URL. section 4.3.2
Use a dedicated FlagSet to keep CLI behavior explicit and testable:
- Prefer NewFlagSet over package-level registration when automatic exits and writes to standard error would make tests harder. section 4.3.1
- Read positional arguments with Arg only after Parse; parsing stops at the first nonflag argument, so put positional arguments after flags. section 4.5.1
- Set Usage for a command syntax that includes positional arguments, and write through Output while deriving the command name with Name. section 4.5.2
- Register custom parsers with Var by implementing flag.Value; TextVar can use text marshaling interfaces for values such as IP addresses. section 4.3.2 section 4.8
Usage for options plus a required argument
When a URL is positional rather than a registered flag, assign Usage a function that prints "usage: hit [options] url" using fs.Name(), then call fs.PrintDefaults(). Writing with fs.Output() keeps usage and FlagSet error output together. section 4.5.2
Separate FlagSet instances can model subcommands: give each subcommand its own flags and parse only that subcommand’s flags and arguments. This keeps command-specific options from being treated as one global set. section 4.7
