← 中文资源

简体中文版本

flag.Visit 找出显式设置的旗标

flag.Visit 只遍历调用方显式传入的旗标,配合 VisitAll 还能列出仍取默认值的那些项,帮助输出与配置回显从此分得清清楚楚。

阅读英文原文

实现说明

flag.Visit 找出显式设置的旗标可以归结为函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 explicit: -、defaults:、effective timeout:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「flag.Visit 找出显式设置的旗标」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 explicit: -、defaults:、effective timeout: 标签标明各步骤。

核心语句

untouched = append(untouched, f.Name+"="+f.Value.String())

代码示例

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)
}