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:
flag
package:import "flag"
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.
flag
package's Parse()
function:func main() {
flag.Parse()
// ...
}
This will scan the command-line arguments and set the value of the defined flags.
fmt.Println("Flag value:", myFlag)
// ...
$ 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/