The Go FlagSet package is a library used for parsing command-line arguments. It provides a way to define flags with values and arguments in a structured manner, enabling easy access to these values from other parts of the program.
Example 1:
package main
import ( "flag" "fmt" )
func main() { name := flag.String("name", "default name", "Name of the person") age := flag.Int("age", 25, "Age of the person") flag.Parse()
In this example, we define two flags: `name` and `age`. Both are defined with a default value and a short description. Then we use `flag.Parse()` to parse the arguments provided to the program. We can then access the values of the flags using the pointers returned by the flag functions.
Example 2:
package main
import ( "flag" "fmt" )
func main() { fs := flag.NewFlagSet("my-program", flag.ExitOnError) name := fs.String("name", "default name", "Name of the person") age := fs.Int("age", 25, "Age of the person")
In this example, we create a new FlagSet object and define our flags using the object's methods. We then explicitly call `fs.Parse()` with a slice of strings to parse instead of using the default `flag.Parse()`. This allows us to parse different sets of arguments for different FlagSets.
The Go FlagSet package is part of the standard Go library.
Golang FlagSet - 30 examples found. These are the top rated real world Golang examples of flag.FlagSet extracted from open source projects. You can rate examples to help us improve the quality of examples.