Package flag
Overview ▸
Index ▸
Variables
ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.
var ErrHelp = errors.New("flag: help requested")
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.
var Usage = func() {
fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0])
PrintDefaults()
}
errParse is returned by Set if a flag's value fails to parse, such as with an invalid integer for Int. It then gets wrapped through failf to provide more information.
var errParse = errors.New("parse error")
errRange is returned by Set if a flag's value is out of range. It then gets wrapped through failf to provide more information.
var errRange = errors.New("value out of range")
func Arg
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
func Args() []string
Args returns the non-flag command-line arguments.
func Bool
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 BoolFunc 1.21
func BoolFunc(name, usage string, fn func(string) error)
BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
▸ Example
func BoolVar
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
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
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
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
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 Func 1.16
func Func(name, usage string, fn func(string) error)
Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
▸ Example
func Int
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
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
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
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
func NArg() int
NArg is the number of arguments remaining after flags have been processed.
func NFlag
func NFlag() int
NFlag returns the number of command-line flags that have been set.
func Parse
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
func Parsed() bool
Parsed reports whether the command-line flags have been parsed.
func PrintDefaults
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
-x int 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
flag.String("I", "", "search `directory` for include files")
the output will be
-I directory search directory for include files.
To change the destination for flag messages, call CommandLine.SetOutput.
func Set
func Set(name, value string) error
Set sets the value of the named command-line flag.
func String
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
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 TextVar 1.19
func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)
TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.
▸ Example
func Uint
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
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
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
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.5
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
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
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
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.
func commandLineUsage
func commandLineUsage()
func init
func init()
func isZeroValue
func isZeroValue(flag *Flag, value string) (ok bool, err error)
isZeroValue determines whether the string represents the zero value for a flag.
func numError
func numError(err error) error
type ErrorHandling
ErrorHandling defines how FlagSet.Parse behaves if the parse fails.
type ErrorHandling int
These constants cause FlagSet.Parse to behave as described if the parse fails.
const (
ContinueOnError ErrorHandling = iota // Return a descriptive error.
ExitOnError // Call os.Exit(2) or for -h/-help Exit(0).
PanicOnError // Call panic with a descriptive error.
)
type Flag
A Flag represents the state of a flag.
type Flag struct {
Name string // name as it appears on command line
Usage string // help message
Value Value // value as set
DefValue string // default value (as text); for usage message
}
func Lookup
func Lookup(name string) *Flag
Lookup returns the Flag structure of the named command-line flag, returning nil if none exists.
func sortFlags
func sortFlags(flags map[string]*Flag) []*Flag
sortFlags returns the flags as a slice in lexicographical sorted order.
type FlagSet
A FlagSet represents a set of defined flags. The zero value of a FlagSet has no name and has ContinueOnError error handling.
Flag names must be unique within a FlagSet. An attempt to define a flag whose name is already in use will cause a panic.
type FlagSet struct {
// Usage is the function called when an error occurs while parsing flags.
// The field is a function (not a method) that may be changed to point to
// a custom error handler. What happens after Usage is called depends
// on the ErrorHandling setting; for the command line, this defaults
// to ExitOnError, which exits the program after calling Usage.
Usage func()
name string
parsed bool
actual map[string]*Flag
formal map[string]*Flag
args []string // arguments after flags
errorHandling ErrorHandling
output io.Writer // nil means stderr; use Output() accessor
undef map[string]string // flags which didn't exist at the time of Set
}
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.
var CommandLine *FlagSet
▸ Example
func NewFlagSet
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
NewFlagSet returns a new, empty flag set with the specified name and error handling property. If the name is not empty, it will be printed in the default usage message and in error messages.
func (*FlagSet) Arg
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
func (f *FlagSet) Args() []string
Args returns the non-flag arguments.
func (*FlagSet) Bool
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) BoolFunc 1.21
func (f *FlagSet) BoolFunc(name, usage string, fn func(string) error)
BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func (*FlagSet) BoolVar
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
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
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.10
func (f *FlagSet) ErrorHandling() ErrorHandling
ErrorHandling returns the error handling behavior of the flag set.
func (*FlagSet) Float64
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
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) Func 1.16
func (f *FlagSet) Func(name, usage string, fn func(string) error)
Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.
func (*FlagSet) Init
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
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
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
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
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
func (f *FlagSet) Lookup(name string) *Flag
Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (*FlagSet) NArg
func (f *FlagSet) NArg() int
NArg is the number of arguments remaining after flags have been processed.
func (*FlagSet) NFlag
func (f *FlagSet) NFlag() int
NFlag returns the number of flags that have been set.
func (*FlagSet) Name 1.10
func (f *FlagSet) Name() string
Name returns the name of the flag set.
func (*FlagSet) Output 1.10
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
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
func (f *FlagSet) Parsed() bool
Parsed reports whether f.Parse has been called.
func (*FlagSet) PrintDefaults
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
func (f *FlagSet) Set(name, value string) error
Set sets the value of the named flag.
func (*FlagSet) SetOutput
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
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
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) TextVar 1.19
func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)
TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.
func (*FlagSet) Uint
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
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
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
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
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
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
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.
func (*FlagSet) defaultUsage
func (f *FlagSet) defaultUsage()
defaultUsage is the default function to print a usage message.
func (*FlagSet) failf
func (f *FlagSet) failf(format string, a ...any) error
failf prints to standard error a formatted error and usage message and returns the error.
func (*FlagSet) parseOne
func (f *FlagSet) parseOne() (bool, error)
parseOne parses one flag. It reports whether a flag was seen.
func (*FlagSet) set
func (f *FlagSet) set(name, value string) error
func (*FlagSet) sprintf
func (f *FlagSet) sprintf(format string, a ...any) string
sprintf formats the message, prints it to output, and returns it.
func (*FlagSet) usage
func (f *FlagSet) usage()
usage calls the Usage method for the flag set if one is specified, or the appropriate default usage function otherwise.
type Getter 1.2
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, except the type used by Func.
type Getter interface {
Value
Get() any
}
type Value
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.
type Value interface {
String() string
Set(string) error
}
▸ Example
type boolFlag
optional interface to indicate boolean flags that can be supplied without "=value" text
type boolFlag interface {
Value
IsBoolFlag() bool
}
type boolFuncValue
-- boolFunc Value
type boolFuncValue func(string) error
func (boolFuncValue) IsBoolFlag
func (f boolFuncValue) IsBoolFlag() bool
func (boolFuncValue) Set
func (f boolFuncValue) Set(s string) error
func (boolFuncValue) String
func (f boolFuncValue) String() string
type boolValue
-- bool Value
type boolValue bool
func newBoolValue
func newBoolValue(val bool, p *bool) *boolValue
func (*boolValue) Get
func (b *boolValue) Get() any
func (*boolValue) IsBoolFlag
func (b *boolValue) IsBoolFlag() bool
func (*boolValue) Set
func (b *boolValue) Set(s string) error
func (*boolValue) String
func (b *boolValue) String() string
type durationValue
-- time.Duration Value
type durationValue time.Duration
func newDurationValue
func newDurationValue(val time.Duration, p *time.Duration) *durationValue
func (*durationValue) Get
func (d *durationValue) Get() any
func (*durationValue) Set
func (d *durationValue) Set(s string) error
func (*durationValue) String
func (d *durationValue) String() string
type float64Value
-- float64 Value
type float64Value float64
func newFloat64Value
func newFloat64Value(val float64, p *float64) *float64Value
func (*float64Value) Get
func (f *float64Value) Get() any
func (*float64Value) Set
func (f *float64Value) Set(s string) error
func (*float64Value) String
func (f *float64Value) String() string
type funcValue
-- func Value
type funcValue func(string) error
func (funcValue) Set
func (f funcValue) Set(s string) error
func (funcValue) String
func (f funcValue) String() string
type int64Value
-- int64 Value
type int64Value int64
func newInt64Value
func newInt64Value(val int64, p *int64) *int64Value
func (*int64Value) Get
func (i *int64Value) Get() any
func (*int64Value) Set
func (i *int64Value) Set(s string) error
func (*int64Value) String
func (i *int64Value) String() string
type intValue
-- int Value
type intValue int
func newIntValue
func newIntValue(val int, p *int) *intValue
func (*intValue) Get
func (i *intValue) Get() any
func (*intValue) Set
func (i *intValue) Set(s string) error
func (*intValue) String
func (i *intValue) String() string
type stringValue
-- string Value
type stringValue string
func newStringValue
func newStringValue(val string, p *string) *stringValue
func (*stringValue) Get
func (s *stringValue) Get() any
func (*stringValue) Set
func (s *stringValue) Set(val string) error
func (*stringValue) String
func (s *stringValue) String() string
type textValue
-- encoding.TextUnmarshaler Value
type textValue struct{ p encoding.TextUnmarshaler }
func newTextValue
func newTextValue(val encoding.TextMarshaler, p encoding.TextUnmarshaler) textValue
func (textValue) Get
func (v textValue) Get() any
func (textValue) Set
func (v textValue) Set(s string) error
func (textValue) String
func (v textValue) String() string
type uint64Value
-- uint64 Value
type uint64Value uint64
func newUint64Value
func newUint64Value(val uint64, p *uint64) *uint64Value
func (*uint64Value) Get
func (i *uint64Value) Get() any
func (*uint64Value) Set
func (i *uint64Value) Set(s string) error
func (*uint64Value) String
func (i *uint64Value) String() string
type uintValue
-- uint Value
type uintValue uint
func newUintValue
func newUintValue(val uint, p *uint) *uintValue
func (*uintValue) Get
func (i *uintValue) Get() any
func (*uintValue) Set
func (i *uintValue) Set(s string) error
func (*uintValue) String
func (i *uintValue) String() string