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.

GoCli Tooling

Code

gosnippet
32 lines
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

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:`.