liveBook · Manning

Flag.Value

As explained in Go by Example

flag.Value is a Go interface for parsing a command-line flag string and assigning the resulting value to an associated variable.

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

How Go by Example covers it

How deep it goes
Defines String and Set, explains their FlagSet lifecycle, and applies custom validation through Var.
Examples
Uses integer, string, and boolean parsers plus a positive-integer parser for request count, concurrency, and rate flags.
What it assumes
Assumes familiarity with FlagSet flags and associated variables while relying on built-in parsers for standard types.
What you can do after
Build custom command-line validation with Go's flag.FlagSet.Var method.
How it connects
Connects command-line flags with Flag, FlagSet, IntVar, Var, built-in value parsers, and custom validation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.