Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Struct ¶
func Struct(s interface{}, prefixes ...string)
Struct creates command line flags (using the standard lib flag package) that set fields of s, prefixed with prefixes separated by dots. The flag name is the field name but with the first letter lowercased (unless the second letter is uppercase as well) and in case of struct fields prefixed with the field name. For example,
MyField bool
would give the flag
-myField
and the field CPU.Bla in
type CPU struct{ Bla bool }
type Conf { CPU; MyField bool }
would have the flag
-CPU.bla
Current contents of s are used as default values, and the struct tag "usage" can be used to provide usage texts for flags. Struct can be called multiple times before flag.Parse() is called.
s will be mutated when flag.Parse() is called.
Note that Struct doesn't support UTF8/Unicode field names
Example ¶
// CAPSExample is going to be embedded in Conf
type CAPSExample struct {
InHere int `usage:"struct fields' fields get prefixed with the containing field's name"`
}
// AnotherEmbed is also going to be embedded
type AnotherEmbed struct {
Ding bool `usage:"does stuff"`
Another int `usage:"frob"`
}
type Conf struct {
// this field has the flag -boolFlag
BoolFlag bool `usage:"this flag is a boolean"`
FloatFlag float64 `usage:"and this one is a float"`
// flags for CAPSExample are prefixed with "CAPSExample", eg. -CAPSExample.inHere
CAPSExample
// flags for AnotherEmbed are prefixed with "anotherEmbed", eg. -anotherEmbed.ding
AnotherEmbed
}
conf := &Conf{
BoolFlag: true,
FloatFlag: 1.0,
CAPSExample: CAPSExample{1},
// fields in AnotherEmbed will default to their zero values, false and 0
}
// create all the flags and "bind" them to conf's fields. The values in conf at the time when
// Struct is called will be used as defaults
Struct(conf)
flag.Parse()
// conf now has values passed in from the command line
flagSet := flag.CommandLine
// get the usage text for the flag -CAPSExample.inHere
f := flagSet.Lookup("CAPSExample.inHere")
fmt.Print(f.Usage)
Output: struct fields' fields get prefixed with the containing field's name
Types ¶
This section is empty.