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

In Go, you can define and parse string command-line flags using the flag package from the standard library. Here's a step-by-step guide on how to do it:

  1. Import the flag package:
import "flag"
  1. Define the command-line flags using the flag package's StringVar() function:
var ( myFlag string ) func init() { flag.StringVar(&myFlag, "flagname", "default value", "description of flag") }

This example defines a flag named "flagname" with a default value of "default value" and a description of "description of flag". The value of the flag will be stored in the myFlag variable.

  1. Parse the command-line flags using the flag package's Parse() function:
func main() { flag.Parse() // ... }

This will scan the command-line arguments and set the value of the defined flags.

  1. Access the value of the flag in your code:
fmt.Println("Flag value:", myFlag) // ...
  1. Compile and run your Go program, passing the command-line flag when executing the program:
$ go run main.go -flagname=myvalue

The program will then output the value of the flag.

You can also use other types of flags like IntVar(), BoolVar(), etc., depending on your needs. Check out the documentation of the flag package for more details: https://golang.org/pkg/flag/