version: 1.10

package flag

import "flag"

Overview

Package flag implements command-line flag parsing.

Usage:

Define flags using flag.String(), Bool(), Int(), etc.

This declares an integer flag, -flagname, stored in the pointer ip, with type
*int.

  1. import "flag"
  2. var ip = flag.Int("flagname", 1234, "help message for flagname")

If you like, you can bind the flag to a variable using the Var() functions.

  1. var flagvar int
  2. func init() {
  3. flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
  4. }

Or you can create custom flags that satisfy the Value interface (with pointer
receivers) and couple them to flag parsing by

  1. flag.Var(&flagVal, "name", "help message for flagname")

For such flags, the default value is just the initial value of the variable.

After all flags are defined, call

  1. flag.Parse()

to parse the command line into the defined flags.

Flags may then be used directly. If you’re using the flags themselves, they are
all pointers; if you bind to variables, they’re values.

  1. fmt.Println("ip has value ", *ip)
  2. fmt.Println("flagvar has value ", flagvar)

After parsing, the arguments following the flags are available as the slice
flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0
through flag.NArg()-1.

Command line flag syntax:

  1. -flag
  2. -flag=x
  3. -flag x // non-boolean flags only

One or two minus signs may be used; they are equivalent. The last form is not
permitted for boolean flags because the meaning of the command

  1. cmd -x *

where * is a Unix shell wildcard, will change if there is a file called 0,
false, etc. You must use the -flag=false form to turn off a boolean flag.

Flag parsing stops just before the first non-flag argument (“-“ is a non-flag
argument) or after the terminator “—“.

Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags may
be:

  1. 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False

Duration flags accept any input valid for time.ParseDuration.

The default set of command-line flags is controlled by top-level functions. The
FlagSet type allows one to define independent sets of flags, such as to
implement subcommands in a command-line interface. The methods of FlagSet are
analogous to the top-level functions for the command-line flag set.


Example:

  1. // These examples demonstrate more intricate uses of the flag package.
  2. package flag_test
  3. import (
  4. "errors"
  5. "flag"
  6. "fmt"
  7. "strings"
  8. "time"
  9. )
  10. // Example 1: A single string flag called "species" with default value "gopher".
  11. var species = flag.String("species", "gopher", "the species we are studying")
  12. // Example 2: Two flags sharing a variable, so we can have a shorthand.
  13. // The order of initialization is undefined, so make sure both use the
  14. // same default value. They must be set up with an init function.
  15. var gopherType string
  16. func init() {
  17. const (
  18. defaultGopher = "pocket"
  19. usage = "the variety of gopher"
  20. )
  21. flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage)
  22. flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)")
  23. }
  24. // Example 3: A user-defined flag type, a slice of durations.
  25. type interval []time.Duration
  26. // String is the method to format the flag's value, part of the flag.Value interface.
  27. // The String method's output will be used in diagnostics.
  28. func (i *interval) String() string {
  29. return fmt.Sprint(*i)
  30. }
  31. // Set is the method to set the flag value, part of the flag.Value interface.
  32. // Set's argument is a string to be parsed to set the flag.
  33. // It's a comma-separated list, so we split it.
  34. func (i *interval) Set(value string) error {
  35. // If we wanted to allow the flag to be set multiple times,
  36. // accumulating values, we would delete this if statement.
  37. // That would permit usages such as
  38. // -deltaT 10s -deltaT 15s
  39. // and other combinations.
  40. if len(*i) > 0 {
  41. return errors.New("interval flag already set")
  42. }
  43. for _, dt := range strings.Split(value, ",") {
  44. duration, err := time.ParseDuration(dt)
  45. if err != nil {
  46. return err
  47. }
  48. *i = append(*i, duration)
  49. }
  50. return nil
  51. }
  52. // Define a flag to accumulate durations. Because it has a special type,
  53. // we need to use the Var function and therefore create the flag during
  54. // init.
  55. var intervalFlag interval
  56. func init() {
  57. // Tie the command-line flag to the intervalFlag variable and
  58. // set a usage message.
  59. flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
  60. }
  61. func Example() {
  62. // All the interesting pieces are with the variables declared above, but
  63. // to enable the flag package to see the flags defined there, one must
  64. // execute, typically at the start of main (not init!):
  65. // flag.Parse()
  66. // We don't run it here because this is not a main function and
  67. // the testing suite has already parsed the flags.
  68. }

Index

Examples

Package files

flag.go

Variables

  1. var CommandLine = NewFlagSet(os.Args[0], ExitOnError)

CommandLine is the default set of command-line flags, parsed from os.Args. The
top-level functions such as BoolVar, Arg, and so on are wrappers for the methods
of CommandLine.

  1. var ErrHelp = errors.New("flag: help requested")

ErrHelp is the error returned if the -help or -h flag is invoked but no such
flag is defined.

  1. var Usage = func() {
  2. fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0])
  3. PrintDefaults()
  4. }

Usage prints a usage message documenting all defined command-line flags to
CommandLine’s output, which by default is os.Stderr. It is called when an error
occurs while parsing flags. The function is a variable that may be changed to
point to a custom function. By default it prints a simple header and calls
PrintDefaults; for details about the format of the output and how to control it,
see the documentation for PrintDefaults. Custom usage functions may choose to
exit the program; by default exiting happens anyway as the command line’s error
handling strategy is set to ExitOnError.

func Arg

  1. func Arg(i int) string

Arg returns the i’th command-line argument. Arg(0) is the first remaining
argument after flags have been processed. Arg returns an empty string if the
requested element does not exist.

func Args

  1. func Args() []string

Args returns the non-flag command-line arguments.

func Bool

  1. func Bool(name string, value bool, usage string) *bool

Bool defines a bool flag with specified name, default value, and usage string.
The return value is the address of a bool variable that stores the value of the
flag.

func BoolVar

  1. func BoolVar(p *bool, name string, value bool, usage string)

BoolVar defines a bool flag with specified name, default value, and usage
string. The argument p points to a bool variable in which to store the value of
the flag.

func Duration

  1. func Duration(name string, value time.Duration, usage string) *time.Duration

Duration defines a time.Duration flag with specified name, default value, and
usage string. The return value is the address of a time.Duration variable that
stores the value of the flag. The flag accepts a value acceptable to
time.ParseDuration.

func DurationVar

  1. func DurationVar(p *time.Duration, name string, value time.Duration, usage string)

DurationVar defines a time.Duration flag with specified name, default value, and
usage string. The argument p points to a time.Duration variable in which to
store the value of the flag. The flag accepts a value acceptable to
time.ParseDuration.

func Float64

  1. func Float64(name string, value float64, usage string) *float64

Float64 defines a float64 flag with specified name, default value, and usage
string. The return value is the address of a float64 variable that stores the
value of the flag.

func Float64Var

  1. func Float64Var(p *float64, name string, value float64, usage string)

Float64Var defines a float64 flag with specified name, default value, and usage
string. The argument p points to a float64 variable in which to store the value
of the flag.

func Int

  1. func Int(name string, value int, usage string) *int

Int defines an int flag with specified name, default value, and usage string.
The return value is the address of an int variable that stores the value of the
flag.

func Int64

  1. func Int64(name string, value int64, usage string) *int64

Int64 defines an int64 flag with specified name, default value, and usage
string. The return value is the address of an int64 variable that stores the
value of the flag.

func Int64Var

  1. func Int64Var(p *int64, name string, value int64, usage string)

Int64Var defines an int64 flag with specified name, default value, and usage
string. The argument p points to an int64 variable in which to store the value
of the flag.

func IntVar

  1. func IntVar(p *int, name string, value int, usage string)

IntVar defines an int flag with specified name, default value, and usage string.
The argument p points to an int variable in which to store the value of the
flag.

func NArg

  1. func NArg() int

NArg is the number of arguments remaining after flags have been processed.

func NFlag

  1. func NFlag() int

NFlag returns the number of command-line flags that have been set.

func Parse

  1. func Parse()

Parse parses the command-line flags from os.Args[1:]. Must be called after all
flags are defined and before flags are accessed by the program.

func Parsed

  1. func Parsed() bool

Parsed reports whether the command-line flags have been parsed.

func PrintDefaults

  1. func PrintDefaults()

PrintDefaults prints, to standard error unless configured otherwise, a usage
message showing the default settings of all defined command-line flags. For an
integer valued flag x, the default output has the form

  1. -x int
  2. usage-message-for-x (default 7)

The usage message will appear on a separate line for anything but a bool flag
with a one-byte name. For bool flags, the type is omitted and if the flag name
is one byte the usage message appears on the same line. The parenthetical
default is omitted if the default is the zero value for the type. The listed
type, here int, can be changed by placing a back-quoted name in the flag’s usage
string; the first such item in the message is taken to be a parameter name to
show in the message and the back quotes are stripped from the message when
displayed. For instance, given

  1. flag.String("I", "", "search `directory` for include files")

the output will be

  1. -I directory
  2. search directory for include files.

func Set

  1. func Set(name, value string) error

Set sets the value of the named command-line flag.

func String

  1. func String(name string, value string, usage string) *string

String defines a string flag with specified name, default value, and usage
string. The return value is the address of a string variable that stores the
value of the flag.

func StringVar

  1. func StringVar(p *string, name string, value string, usage string)

StringVar defines a string flag with specified name, default value, and usage
string. The argument p points to a string variable in which to store the value
of the flag.

func Uint

  1. func Uint(name string, value uint, usage string) *uint

Uint defines a uint flag with specified name, default value, and usage string.
The return value is the address of a uint variable that stores the value of the
flag.

func Uint64

  1. func Uint64(name string, value uint64, usage string) *uint64

Uint64 defines a uint64 flag with specified name, default value, and usage
string. The return value is the address of a uint64 variable that stores the
value of the flag.

func Uint64Var

  1. func Uint64Var(p *uint64, name string, value uint64, usage string)

Uint64Var defines a uint64 flag with specified name, default value, and usage
string. The argument p points to a uint64 variable in which to store the value
of the flag.

func UintVar

  1. func UintVar(p *uint, name string, value uint, usage string)

UintVar defines a uint flag with specified name, default value, and usage
string. The argument p points to a uint variable in which to store the value of
the flag.

func UnquoteUsage

  1. func UnquoteUsage(flag *Flag) (name string, usage string)

UnquoteUsage extracts a back-quoted name from the usage string for a flag and
returns it and the un-quoted usage. Given “a name to show” it returns (“name”,
“a name to show”). If there are no back quotes, the name is an educated guess of
the type of the flag’s value, or the empty string if the flag is boolean.

func Var

  1. func Var(value Value, name string, usage string)

Var defines a flag with the specified name and usage string. The type and value
of the flag are represented by the first argument, of type Value, which
typically holds a user-defined implementation of Value. For instance, the caller
could create a flag that turns a comma-separated string into a slice of strings
by giving the slice the methods of Value; in particular, Set would decompose the
comma-separated string into the slice.

func Visit

  1. func Visit(fn func(*Flag))

Visit visits the command-line flags in lexicographical order, calling fn for
each. It visits only those flags that have been set.

func VisitAll

  1. func VisitAll(fn func(*Flag))

VisitAll visits the command-line flags in lexicographical order, calling fn for
each. It visits all flags, even those not set.

type ErrorHandling

  1. type ErrorHandling int

ErrorHandling defines how FlagSet.Parse behaves if the parse fails.

  1. const (
  2. ContinueOnError ErrorHandling = iota // Return a descriptive error.
  3. ExitOnError // Call os.Exit(2).
  4. PanicOnError // Call panic with a descriptive error.
  5. )

These constants cause FlagSet.Parse to behave as described if the parse fails.

type Flag

  1. type Flag struct {
  2. Name string // name as it appears on command line
  3. Usage string // help message
  4. Value Value // value as set
  5. DefValue string // default value (as text); for usage message
  6. }

A Flag represents the state of a flag.

func Lookup

  1. func Lookup(name string) *Flag

Lookup returns the Flag structure of the named command-line flag, returning nil
if none exists.

type FlagSet

  1. type FlagSet struct {
  2. // Usage is the function called when an error occurs while parsing flags.
  3. // The field is a function (not a method) that may be changed to point to
  4. // a custom error handler. What happens after Usage is called depends
  5. // on the ErrorHandling setting; for the command line, this defaults
  6. // to ExitOnError, which exits the program after calling Usage.
  7. Usage func()
  8. // contains filtered or unexported fields
  9. }

A FlagSet represents a set of defined flags. The zero value of a FlagSet has no
name and has ContinueOnError error handling.

func NewFlagSet

  1. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

NewFlagSet returns a new, empty flag set with the specified name and error
handling property.

func (*FlagSet) Arg

  1. func (f *FlagSet) Arg(i int) string

Arg returns the i’th argument. Arg(0) is the first remaining argument after
flags have been processed. Arg returns an empty string if the requested element
does not exist.

func (*FlagSet) Args

  1. func (f *FlagSet) Args() []string

Args returns the non-flag arguments.

func (*FlagSet) Bool

  1. func (f *FlagSet) Bool(name string, value bool, usage string) *bool

Bool defines a bool flag with specified name, default value, and usage string.
The return value is the address of a bool variable that stores the value of the
flag.

func (*FlagSet) BoolVar

  1. func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)

BoolVar defines a bool flag with specified name, default value, and usage
string. The argument p points to a bool variable in which to store the value of
the flag.

func (*FlagSet) Duration

  1. func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration

Duration defines a time.Duration flag with specified name, default value, and
usage string. The return value is the address of a time.Duration variable that
stores the value of the flag. The flag accepts a value acceptable to
time.ParseDuration.

func (*FlagSet) DurationVar

  1. func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)

DurationVar defines a time.Duration flag with specified name, default value, and
usage string. The argument p points to a time.Duration variable in which to
store the value of the flag. The flag accepts a value acceptable to
time.ParseDuration.

func (*FlagSet) ErrorHandling

  1. func (f *FlagSet) ErrorHandling() ErrorHandling

ErrorHandling returns the error handling behavior of the flag set.

func (*FlagSet) Float64

  1. func (f *FlagSet) Float64(name string, value float64, usage string) *float64

Float64 defines a float64 flag with specified name, default value, and usage
string. The return value is the address of a float64 variable that stores the
value of the flag.

func (*FlagSet) Float64Var

  1. func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)

Float64Var defines a float64 flag with specified name, default value, and usage
string. The argument p points to a float64 variable in which to store the value
of the flag.

func (*FlagSet) Init

  1. func (f *FlagSet) Init(name string, errorHandling ErrorHandling)

Init sets the name and error handling property for a flag set. By default, the
zero FlagSet uses an empty name and the ContinueOnError error handling policy.

func (*FlagSet) Int

  1. func (f *FlagSet) Int(name string, value int, usage string) *int

Int defines an int flag with specified name, default value, and usage string.
The return value is the address of an int variable that stores the value of the
flag.

func (*FlagSet) Int64

  1. func (f *FlagSet) Int64(name string, value int64, usage string) *int64

Int64 defines an int64 flag with specified name, default value, and usage
string. The return value is the address of an int64 variable that stores the
value of the flag.

func (*FlagSet) Int64Var

  1. func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)

Int64Var defines an int64 flag with specified name, default value, and usage
string. The argument p points to an int64 variable in which to store the value
of the flag.

func (*FlagSet) IntVar

  1. func (f *FlagSet) IntVar(p *int, name string, value int, usage string)

IntVar defines an int flag with specified name, default value, and usage string.
The argument p points to an int variable in which to store the value of the
flag.

func (*FlagSet) Lookup

  1. func (f *FlagSet) Lookup(name string) *Flag

Lookup returns the Flag structure of the named flag, returning nil if none
exists.

func (*FlagSet) NArg

  1. func (f *FlagSet) NArg() int

NArg is the number of arguments remaining after flags have been processed.

func (*FlagSet) NFlag

  1. func (f *FlagSet) NFlag() int

NFlag returns the number of flags that have been set.

func (*FlagSet) Name

  1. func (f *FlagSet) Name() string

Name returns the name of the flag set.

func (*FlagSet) Output

  1. func (f *FlagSet) Output() io.Writer

Output returns the destination for usage and error messages. os.Stderr is
returned if output was not set or was set to nil.

func (*FlagSet) Parse

  1. func (f *FlagSet) Parse(arguments []string) error

Parse parses flag definitions from the argument list, which should not include
the command name. Must be called after all flags in the FlagSet are defined and
before flags are accessed by the program. The return value will be ErrHelp if
-help or -h were set but not defined.

func (*FlagSet) Parsed

  1. func (f *FlagSet) Parsed() bool

Parsed reports whether f.Parse has been called.

func (*FlagSet) PrintDefaults

  1. func (f *FlagSet) PrintDefaults()

PrintDefaults prints, to standard error unless configured otherwise, the default
values of all defined command-line flags in the set. See the documentation for
the global function PrintDefaults for more information.

func (*FlagSet) Set

  1. func (f *FlagSet) Set(name, value string) error

Set sets the value of the named flag.

func (*FlagSet) SetOutput

  1. func (f *FlagSet) SetOutput(output io.Writer)

SetOutput sets the destination for usage and error messages. If output is nil,
os.Stderr is used.

func (*FlagSet) String

  1. func (f *FlagSet) String(name string, value string, usage string) *string

String defines a string flag with specified name, default value, and usage
string. The return value is the address of a string variable that stores the
value of the flag.

func (*FlagSet) StringVar

  1. func (f *FlagSet) StringVar(p *string, name string, value string, usage string)

StringVar defines a string flag with specified name, default value, and usage
string. The argument p points to a string variable in which to store the value
of the flag.

func (*FlagSet) Uint

  1. func (f *FlagSet) Uint(name string, value uint, usage string) *uint

Uint defines a uint flag with specified name, default value, and usage string.
The return value is the address of a uint variable that stores the value of the
flag.

func (*FlagSet) Uint64

  1. func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64

Uint64 defines a uint64 flag with specified name, default value, and usage
string. The return value is the address of a uint64 variable that stores the
value of the flag.

func (*FlagSet) Uint64Var

  1. func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)

Uint64Var defines a uint64 flag with specified name, default value, and usage
string. The argument p points to a uint64 variable in which to store the value
of the flag.

func (*FlagSet) UintVar

  1. func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)

UintVar defines a uint flag with specified name, default value, and usage
string. The argument p points to a uint variable in which to store the value of
the flag.

func (*FlagSet) Var

  1. func (f *FlagSet) Var(value Value, name string, usage string)

Var defines a flag with the specified name and usage string. The type and value
of the flag are represented by the first argument, of type Value, which
typically holds a user-defined implementation of Value. For instance, the caller
could create a flag that turns a comma-separated string into a slice of strings
by giving the slice the methods of Value; in particular, Set would decompose the
comma-separated string into the slice.

func (*FlagSet) Visit

  1. func (f *FlagSet) Visit(fn func(*Flag))

Visit visits the flags in lexicographical order, calling fn for each. It visits
only those flags that have been set.

func (*FlagSet) VisitAll

  1. func (f *FlagSet) VisitAll(fn func(*Flag))

VisitAll visits the flags in lexicographical order, calling fn for each. It
visits all flags, even those not set.

type Getter

  1. type Getter interface {
  2. Value
  3. Get() interface{}
  4. }

Getter is an interface that allows the contents of a Value to be retrieved. It
wraps the Value interface, rather than being part of it, because it appeared
after Go 1 and its compatibility rules. All Value types provided by this package
satisfy the Getter interface.

type Value

  1. type Value interface {
  2. String() string
  3. Set(string) error
  4. }

Value is the interface to the dynamic value stored in a flag. (The default value
is represented as a string.)

If a Value has an IsBoolFlag() bool method returning true, the command-line
parser makes -name equivalent to -name=true rather than using the next
command-line argument.

Set is called once, in command line order, for each flag present. The flag
package may call the String method with a zero-valued receiver, such as a nil
pointer.