import ( "flag" "fmt" ) func main() { var name string var age int var male bool fs := flag.NewFlagSet("", flag.ExitOnError) fs.StringVar(&name, "name", "John", "Enter a name") fs.IntVar(&age, "age", 20, "Enter an age") fs.BoolVar(&male, "male", true, "Enter gender") fs.Parse(os.Args[1:]) fmt.Println("Name:", name) fmt.Println("Age:", age) fmt.Println("Gender:", male) fmt.Println("Number of other args:", fs.NArg()) }
import ( "flag" "fmt" "os" ) func main() { fs := flag.NewFlagSet("", flag.ExitOnError) help := fs.Bool("help", false, "Display help text") num := fs.Int("num", 0, "Enter a number") fs.Parse(os.Args[1:]) if *help { fmt.Println("Usage: myprog [flags] [args] ...") fs.PrintDefaults() return } fmt.Println("Number:", *num) fmt.Println("Other args:", fs.Args()) }This example defines two flags, "help" and "num". We then parse the command-line arguments using "fs.Parse(os.Args[1:])". If the "help" flag was set, we print usage text and the default flags, then return. Otherwise, we print the number variable, followed by the un-parsed arguments. This code example demonstrates the "flag" package library.