How to set and retrieve values for command-line flags programmatically in Go?

In Go, you can use the flag package to define and parse command-line flags. Here's how you can set and retrieve values for command-line flags programmatically:

  1. Import the flag package:
import "flag"
  1. Define the command-line flags using the flag package's functions such as String, Bool, Int, etc. For example, let's define a string flag:
var myFlag string flag.StringVar(&myFlag, "myflag", "default_value", "description of my flag")
  1. Parse the command-line arguments by calling flag.Parse():
flag.Parse()
  1. After parsing, you can retrieve the value of the flag using the declared variable. For example, to retrieve the value of the myflag flag:
fmt.Println("Value of myflag:", myFlag)
  1. Build and execute your Go program, passing the command-line flags. For example:
$ go run main.go -myflag=my_value

The program will output:

Value of myflag: my_value

If you don't provide a value for a flag, it will use the default value you specified during flag definition.

The flag package provides several other functions for defining and retrieving different types of flags. You can refer to the official Go documentation for more details: https://pkg.go.dev/flag