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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.