flag package
Go's standard library package for parsing command-line options into typed values with defaults and a generated usage message.
In more detail
Declare each option, such as tries := flag.Int("tries", 3, "attempts before giving up"), then call flag.Parse() and read the values through the returned pointers. Bad input prints usage and exits with code 2. It accepts -name or --name, but not bundled single-letter options.
Example
tries := flag.Int("tries", 3, "attempts before giving up")
flag.Parse()
fmt.Println(*tries)Related terms
- command-line option — An argument starting with a dash, such as -r or --help, that changes how a command behaves rather than naming what it works on.
- usage message — The short help text a command prints to standard error when it is run wrongly, showing its syntax and options.
- positional argument — A command-line argument identified by its position rather than by a flag name, such as the host names after the options.
- Cobra — A widely used third-party Go library for building command-line tools with subcommands, nested help and shell completion.
Taught in
- Your First Program and go run — Concurrent Systems Programming with Go
- Parsing Arguments with flag — Concurrent Systems Programming with Go