Flag Visit Reports Explicitly Set Flags
Distinguish user-set flags from declared defaults with flag.Visit and VisitAll, so help output only shows what was actually passed.
Code
package main
import (
"flag"
"fmt"
"strings"
)
func main() {
timeout := flag.Int("timeout", 30, "seconds per request")
retries := flag.Int("retries", 3, "attempts before giving up")
// simulate one invocation: demo --timeout 5
flag.CommandLine.Parse([]string{"--timeout", "5"})
// Visit walks only flags the caller explicitly set, in lexical order
flag.Visit(func(f *flag.Flag) {
fmt.Printf("explicit: -%s=%s\n", f.Name, f.Value.String())
})
// VisitAll covers every declared flag; diff the two to find defaults
explicit := map[string]bool{}
flag.Visit(func(f *flag.Flag) { explicit[f.Name] = true })
var untouched []string
flag.VisitAll(func(f *flag.Flag) {
if !explicit[f.Name] {
untouched = append(untouched, f.Name+"="+f.Value.String())
}
})
fmt.Println("defaults:", strings.Join(untouched, ", "))
fmt.Println("effective timeout:", *timeout, "retries:", *retries)
}Reading the snippet
Flag Visit Reports Explicitly Set Flags keeps everything in the function main.
Applying it
The output lines come labeled — explicit: -, defaults:, effective timeout: — when the file runs.
Statements that matter
untouched = append(untouched, f.Name+"="+f.Value.String())
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 Visit Reports Explicitly Set Flags print when run?
- The script runs standalone; its 3 labeled outputs include `explicit: -`, `defaults:`, `effective timeout:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.