Flag TextVar Parses Typed Values

Durations parse with flag.Duration while TextVar routes richer types like netip.Addr through encoding.TextUnmarshaler, so bad text aborts the run early.

GoCli Tooling

Code

gosnippet
30 lines
package main

import (
	"flag"
	"fmt"
	"net/netip"
	"time"
)

func main() {
	timeout := flag.Duration("timeout", 30*time.Second, "per-request deadline")
	retries := flag.Int("retries", 3, "attempts before giving up")

	// TextVar routes richer types through encoding.TextUnmarshaler, wired into the flag system
	var listen netip.Addr
	flag.TextVar(&listen, "listen", netip.MustParseAddr("127.0.0.1"), "bind address")

	// simulate one invocation: demo --timeout 250ms --listen 10.0.0.7
	flag.CommandLine.Parse([]string{"--timeout", "250ms", "--listen", "10.0.0.7"})

	fmt.Println("timeout:", *timeout)
	fmt.Println("retries:", *retries)
	fmt.Println("listen:", listen)

	// invalid text fails parsing before your code runs
	bad := flag.NewFlagSet("bad", flag.ContinueOnError)
	var addr netip.Addr
	bad.TextVar(&addr, "listen", netip.MustParseAddr("127.0.0.1"), "bind address")
	fmt.Println("bad parse:", bad.Parse([]string{"--listen", "not-an-ip"}))
}

Under the hood

Flag TextVar Parses Typed Values keeps everything in the function main.

Putting it to use

The demo output is labeled (timeout:, retries:, listen:); each label names the call that printed it.

Core lines

flag.TextVar(&listen, "listen", netip.MustParseAddr("127.0.0.1"), "bind address")

Interactive Tools for This Topic

FAQ

What does Flag TextVar Parses Typed Values print when run?
No setup needed: run the file and look for labeled lines like `timeout:`, `retries:`, `listen:` in the output.