How to create and parse flag sets for different parts of a Go program?

To create and parse flag sets for different parts of a Go program, you can make use of the flag package, which is part of the standard library. This package provides functionalities for defining and accessing command-line flags.

Here's a step-by-step guide to creating and parsing flag sets in Go:

Step 1: Import the flag package

import "flag"

Step 2: Define flag variables

Before parsing flags, you need to define variables to hold the flag values. You can define flags at package level or within a specific function, depending on the scope you need.

var ( flag1 = flag.Int("flag1", 123, "Description of flag1") flag2 = flag.String("flag2", "default value", "Description of flag2") )

In the example above, flag1 is defined as an integer flag with a default value of 123, and flag2 is defined as a string flag with a default value of "default value".

Step 3: Parse the flag set

Usually, flags are parsed in the main function before starting the program execution. By default, the flag.Parse() function reads the command-line arguments and sets the flag variables accordingly.

func main() { flag.Parse() // Rest of the program }

Step 4: Access the flag values

After parsing the flag set, you can access the flag values using the defined variables. For example:

func main() { flag.Parse() // Access the flag values value1 := *flag1 value2 := *flag2 // Use the flag values fmt.Println("Flag 1:", value1) fmt.Println("Flag 2:", value2) // Rest of the program }

In the example above, the flag values are accessed using the dereference operator *, as the flag variables are pointers.

Step 5: Run the program with flags

To pass flags and their values, you can run the program from the command-line. For example:

$ go run main.go -flag1=456 -flag2="new value"

This command-line invocation will set flag1 to 456 and flag2 to "new value".

That's it! You have successfully created and parsed flag sets for different parts of your Go program.