How to display usage information for a Go program with defined flags?

To display usage information for a Go program with defined flags, you can use the flag package in Go. Here's an example of how you can do it:

  1. Import the flag package:
import "flag"
  1. Define the flags for your program:
var ( flag1 = flag.String("flag1", "default value", "description for flag1") flag2 = flag.Int("flag2", 0, "description for flag2") // ... define more flags )
  1. Create a function to print the usage information:
func printUsage() { flag.PrintDefaults() }
  1. Parse the command-line arguments:
flag.Parse()
  1. Optionally, you can check if the user has provided the -h or --help flag to print the usage information and exit the program:
if len(os.Args) > 1 && (os.Args[1] == "-h" || os.Args[1] == "--help") { printUsage() os.Exit(0) }

Now, when you run your program with the -h or --help flag, it will display the usage information, including the defined flags and their descriptions.

For example:

$ go run main.go -h Usage of /tmp/go-build1415292925/b001/exe/main: -flag1 string description for flag1 (default "default value") -flag2 int description for flag2 (default 0) ...

Note: Make sure to replace main.go with the actual name of your Go file.