The `flag` package in Go
The flag
package in Go
The flag
package in Go is used to parse command-line flags. Here are some of the most commonly used functions from the flag
package:
-
flag.String()
Defines a string flag with a default value and a description.var name = flag.String("name", "default", "your name") -
flag.Int()
Defines an integer flag with a default value and a description.var age = flag.Int("age", 30, "your age") -
flag.Bool()
Defines a boolean flag with a default value and a description.var verbose = flag.Bool("verbose", false, "enable verbose output") -
flag.Parse()
Parses the command-line flags. This must be called after all flags are defined.flag.Parse() -
flag.Args()
Returns the non-flag arguments after parsing.args := flag.Args() -
flag.NArg()
Returns the number of non-flag arguments.numArgs := flag.NArg() -
flag.NFlag()
Returns the number of flags that have been set.numFlags := flag.NFlag() -
flag.Float64()
Defines a float64 flag with a default value and description.var weight = flag.Float64("weight", 75.5, "your weight in kg") -
flag.Duration()
Defines a duration flag (time.Duration) with a default value and description.var timeout = flag.Duration("timeout", 10*time.Second, "timeout duration") -
flag.Set()
Allows setting a flag programmatically.flag.Set("name", "John") -
flag.Lookup()
Returns the flag with the given name (if it exists).f := flag.Lookup("name")
These functions allow you to define and manage flags in your Go programs, making it easy to handle user input from the command line.