Flag package provides features about command-line flag parsing. It includes a usage message of course. For example, it shows them as following.
package main
import (
"flag"
"os"
)
func main() {
var importFile string
var config bool
var number int
flags := flag.NewFlagSet("mycmd", flag.ExitOnError)
flags.StringVar(&importFile, "import", "", "import file.")
flags.BoolVar(&config, "c", false, "edit config.")
flags.IntVar(&number, "n", 0, "number of executions.")
flags.Parse(os.Args[1:])
}
$ ./mycmd --help
Usage of mycmd:
-c edit config.
-import string
import file.
-n int
number of executions.
This build automatically. The parameter name uses the flag's type. But sometimes want to customize parameter name.
For example, in the example above, I would like to use file
as an argument to -import
and number
as an argument to -n
(Because that is surely more natural ;)).
This can specify from usage
argument xxVar
methods. If includes a back-quoted name in usage
, it uses for the parameter name.
package main
import (
"flag"
"os"
)
func main() {
var importFile string
var config bool
var number int
flags := flag.NewFlagSet("mycmd", flag.ExitOnError)
flags.StringVar(&importFile, "import", "", "Import `file`.")
flags.BoolVar(&config, "c", false, "Edit config.")
flags.IntVar(&number, "n", 0, "`Number` of executions.")
flags.Parse(os.Args[1:])
}
$ ./mycmd --help
Usage of mycmd:
-c edit config.
-import file
import file.
-n number
number of executions.
I didn't know long about this. This describes in the doc of PrintDefaults
func.
I hope this helps someone.
Top comments (0)