Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Logging, Flags and Testing

Go flag package

Reference for the Go flag package: String, Int, Bool, Duration, flag.Parse, FlagSet subcommands, custom flag.Value types, usage text and parsing rules.

The package flag parses command-line options such as -port=8080 -verbose. You declare each flag with a name, a default value and a help text, call flag.Parse(), and read the values. Flags that are not declared cause an error and a usage message.

Each declaration comes in two forms: flag.Int("port", 8080, "...") returns a *int, while flag.IntVar(&port, "port", 8080, "...") stores the value into a variable you own. For programs with subcommands (git commit, git push), create one flag.FlagSet per command.

Go
port := flag.Int("port", 8080, "port to listen on")
flag.Parse()
fmt.Println(*port, flag.Args())

Try it

In a real program, flag.Parse() reads os.Args. The examples below use a FlagSet and pass the arguments explicitly, so they are repeatable here.

Go Declaring and parsing flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Custom flag types and subcommands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func String(name string, value string, usage string) *string
func Int(name string, value int, usage string) *int
func Bool(name string, value bool, usage string) *bool
func Duration(name string, value time.Duration, usage string) *time.Duration
func StringVar(p *string, name string, value string, usage string)
func Var(value Value, name string, usage string)
func Func(name, usage string, fn func(string) error)
func BoolFunc(name, usage string, fn func(string) error) // Go 1.21
func Parse()
func Args() []string
func NArg() int
func Arg(i int) string
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

type Value interface {
	String() string
	Set(string) error
}
Name Description
name Flag name without dashes.
value Default value, used when the flag is absent.
usage Help text shown by -h and PrintDefaults. Backquoted words become the placeholder name: "file to `read`" prints -f read.
ErrorHandling ContinueOnError (return the error), ExitOnError (exit with 2), PanicOnError. The default flag set uses ExitOnError.

Errors: unknown flags, bad values (-port=abc) and -h / -help (returns flag.ErrHelp) produce errors from Parse; with ExitOnError the program prints usage to stderr and exits.

Usage notes

  • Syntax accepted. -name value, --name value, -name=value and --name=value are all valid. Single and double dashes are equivalent.
  • Boolean flags cannot take a separate value: -v false treats false as a positional argument. Write -v=false.
  • Parsing stops at the first argument that does not start with -, or after a bare --. Put flags before file names; the package does not reorder arguments like GNU getopt.
  • No short/long pairs or required flags. Check required flags yourself after parsing (fs.Visit shows which were set), or use a library such as cobra for richer CLIs.
  • Custom types need Set and String. String may be called on a zero value, so make it nil-safe.
  • flag.Usage is a variable you can replace to print your own help text.
  • Environment fallbacks. The package ignores the environment; read os.Getenv for defaults before declaring the flag.
  • Testing. Always parse into a fresh FlagSet in functions you want to test; the global flag set is shared state.