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:
flag
package:import "flag"
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")
flag.Parse()
:flag.Parse()
myflag
flag:fmt.Println("Value of myflag:", myFlag)
$ 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