How to define and parse integer command-line flags in Go?

In Go, you can define and parse integer command-line flags using the flag package. Here's an example of how to do it:

package main import ( "flag" "fmt" ) func main() { // Define an integer flag count := flag.Int("count", 0, "number of items") // Parse the command-line flags flag.Parse() // Access the value of the flag fmt.Println("Count:", *count) }

In this example, we define an integer flag using the Int function from the flag package. The Int function takes three arguments: the name of the flag, the default value, and a brief description.

After defining the flag, we call flag.Parse() to parse the command-line arguments and assign values to the defined flags.

To access the value of the flag, we use the dereference operator (*) to get the value stored at the memory address of the flag variable.

Assuming the above code is saved in a file named main.go, you can run it with the following command:

$ go run main.go -count 10

The output will be:

Count: 10

If you don't provide a value for the flag, it will use the default value (0 in this case).