liveBook · Manning

FlagSet.Var

As explained in Go by Example

FlagSet.Var is a method that registers a named command-line flag backed by a value implementing the flag.Value interface.

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

How Go by Example covers it

How deep it goes
Explains interface registration, Set and String behavior, defaults, errors, and a complete CLI integration, but not parser internals.
Examples
Demonstrates validated request, concurrency, and rate flags in the HIT command, including zero rejection and underscore-separated numbers.
What it assumes
Assumes familiarity with Go command-line flags and interfaces while teaching custom flag.Value implementations from their registration onward.
What you can do after
Build custom command-line validation by implementing flag.Value and registering it with FlagSet.Var.
How it connects
Connects FlagSet.Var with flag.Value, FlagSet, custom parsers, IntVar, StringVar, and validation errors.

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.