How to use flag parsing functions with different flag types in Go?

In Go, the flag package provides a convenient way to parse command-line arguments. You can define various types of flags using the FlagType() functions available in the package. Here is an example of using different flag types:

  1. Define the flags using the appropriate FlagType() function. For example:
// Define a string flag name := flag.String("name", "John Doe", "Specify your name") // Define an integer flag age := flag.Int("age", 0, "Specify your age") // Define a boolean flag isStudent := flag.Bool("student", false, "Specify if you are a student")
  1. Call flag.Parse() to parse the command-line arguments. This will populate the flag variables with values provided as arguments.
flag.Parse()
  1. Use the flag variables in your code as needed. For example:
fmt.Println("Name:", *name) fmt.Println("Age:", *age) fmt.Println("Is Student:", *isStudent)
  1. To run the program with different flags, pass the corresponding command-line arguments. For example:
go run main.go -name "Alice" -age 25 -student

Output:

Name: Alice Age: 25 Is Student: true

Note that for boolean flags, passing the flag without a value sets it to true, while omitting the flag sets it to false.

Additionally, you can customize flag parsing behavior using other functions provided by the flag package, such as flag.StringVar(), flag.Parse() or flag.Usage().