flag.Value is the interface behind Go command-line flag parsers. A Flag stores a Value implementation that converts a string input, assigns the result to an associated variable, and reports parsing errors. section 4.4.1
A Value implementation provides two methods:
- String returns the associated variable as text; FlagSet uses it to obtain a flag’s default value for usage output. section 4.4.1
- Set parses a command-line string, updates the associated variable, and returns an error when the value is invalid. section 4.4.1 section 4.4.3
- Built-in implementations such as stringValue, intValue, and boolValue handle common variable types, while custom implementations add domain-specific validation. section 4.4.1
Validating positive integer flags
A request tool can replace IntVar with a custom positive-integer Value and register it through FlagSet.Var. Initialize the linked variable before calling Var when a default is needed. FlagSet then invokes Set during parsing, rejecting values such as -n 0 with an actionable error while accepting readable forms such as 10_000. section 4.4 section 4.4.3
Listing 4.9 Using FlagSet.Var (hit/cmd/hit/config.go)
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)
}
See a complete parseArgs integration that combines standard StringVar usage with custom Value parsers for request count, concurrency, and rate flags. section 4.4.3
