How to import and use the flag package in Go for command-line argument parsing?

To import and use the flag package in Go for command-line argument parsing, you can follow these steps:

  1. Import the flag package in your code:
import "flag"
  1. Define variables to store the command-line arguments. For example, if you want to accept a string argument named name and an integer argument named age, you can define the variables as follows:
var name string var age int
  1. Use the flag package to define the corresponding command-line flags and bind them to the variables. Use the StringVar function for string flags and the IntVar function for integer flags. For example:
flag.StringVar(&name, "name", "", "Your name") flag.IntVar(&age, "age", 0, "Your age")

Here, the first argument is the variable to bind the flag value to, the second argument is the flag name (including any shorthand notation), the third argument is the default value, and the fourth argument is a short description of the flag.

  1. Parse the command-line arguments using the Parse function of the flag package:
flag.Parse()
  1. Now, you can use the variables name and age to access the parsed command-line arguments.

Here's a complete example that demonstrates how to import and use the flag package:

package main import ( "flag" "fmt" ) func main() { // Define command-line flags var name string var age int flag.StringVar(&name, "name", "", "Your name") flag.IntVar(&age, "age", 0, "Your age") // Parse command-line arguments flag.Parse() // Use the parsed values fmt.Println("Name:", name) fmt.Println("Age:", age) }

In this example, you can run the program with command-line arguments like -name John -age 25 to set the corresponding variables.