Go’s flag package turns raw command-line arguments into ordinary, type-safe variables. Use it when a command needs optional settings—such as request count, concurrency, or a URL—while positional arguments remain separate inputs. A flag name like -n can carry a value such as 100, which becomes an integer variable the program can use directly. section 4.0 section 4.2
Figure 4.2 The flag package parses and saves the command-line arguments set in os.Args by the Go runtime into type-safe regular Go variables that we provide.
Follow the path from arguments placed in os.Args to typed Go variables updated by flag parsing. section 4.2
Create a FlagSet, register each option, then parse the argument slice. A FlagSet associates a flag name with a Flag that holds its usage description, default value, and value parser. Registration methods such as IntVar connect a flag directly to a variable or configuration field; parsing -n=100 then updates that field automatically. section 4.3
Use the package to make a CLI easier to operate and maintain:
- Register flags with sensible defaults so omitted optional settings still produce useful behavior, while users can override those values explicitly. section 4.2.4
- Let built-in parsing, validation, and usage-message support replace repetitive manual handling where the supported syntax fits. section 4.3
- Read positional arguments with FlagSet.Arg and customize help output through FlagSet.Usage when the command needs its own interface details. section 4.8
- Implement flag.Value and register it with FlagSet.Var when a flag needs a custom parser. section 4.8
Configuring an HTTP request tool
A request command can accept -n=1_000_000 and -c=20 before a target URL. The parsed values configure request count and concurrency, allowing one executable to run with different workloads without changing its code. section 4.0



