How to work with command-line flags and arguments in Go?

In Go, command-line flags and arguments are handled using the flag package. The flag package provides a simple and convenient way to define and parse command-line arguments and flags.

To work with command-line flags and arguments in Go, you need to follow these steps:

  1. Import the flag package:
import "flag"
  1. Define your command-line flags using the flag package. You can use the flag package's String, Int, Bool, and other functions to define flags of different types. For example, to define a string flag:
var name string flag.StringVar(&name, "name", "defaultName", "the name to greet")

In this example, we define a string flag named name with a default value of "defaultName". The last argument to StringVar is the usage text that will be displayed when running the program with the -h flag.

  1. Parse the command-line flags by calling flag.Parse(). This will parse the command-line arguments and update the values of your defined flags accordingly. For example:
flag.Parse()
  1. Now, you can access the values of your defined flags. For example, to print the value of the name flag:
fmt.Println("Hello", name)

Here's a complete example that demonstrates the usage of command-line flags and arguments:

package main import ( "flag" "fmt" ) func main() { var name string flag.StringVar(&name, "name", "defaultName", "the name to greet") flag.Parse() fmt.Println("Hello", name) }

Assuming you compile and run the above program, you can pass the name flag as follows:

$ go run main.go -name Alice

This will output:

Hello Alice

If you run the program without passing the name flag, it will use the default value:

$ go run main.go

Output:

Hello defaultName

That's how you can work with command-line flags and arguments in Go using the flag package.