FlagSet.Var registers a named command-line flag backed by a value that implements flag.Value. It connects custom parsing and validation to a FlagSet. section 4.4.3 section 4.8
Use Var when built-in helpers such as IntVar cannot enforce the input rules your command requires:
- Pass a flag.Value implementation, the flag name, and its usage message to Var. section 4.4.3
- Let the FlagSet call the value's Set method to parse and validate user input. section 4.4.3
- Return an actionable error from Set when an argument is invalid. section 4.4.3
- Implement String so Var can obtain the linked variable's default representation for usage output. section 4.4.3
- Initialize the linked variable before calling Var because Var does not accept a separate default-value argument. section 4.4.3
Registering validated integer flags
func parseArgs(c *config, args []string) error { fs := flag.NewFlagSet("hit", flag.ContinueOnError) fs.StringVar(&c.url, "url", "", "HTTP server `URL` (required)") fs.Var(asPositiveIntValue(&c.n), "n", "Number of requests") fs.Var(asPositiveIntValue(&c.c), "c", "Concurrency level") fs.Var(asPositiveIntValue(&c.rps), "rps", "Requests per second") return fs.Parse(args) } Here, a custom positive-integer value rejects `-n 0` with an actionable error instead of allowing a meaningless request count. Numeric parsing can also accept digit separators such as `10_000`. section 4.4.3
