go runtime_error ai_generated true

panic: flag redefined: -verbose

ID: go/flag-redefined-panic

Also available as: JSON · Markdown · 中文
90%Fix Rate
88%Confidence
1Evidence
2023-11-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
go1.20 active
go1.21 active
go1.22 active
go1.23 active

Root Cause

Calling flag.String, flag.Int, or similar with a flag name that has already been registered in the same flag.CommandLine set.

generic

中文

使用已在同一 flag.CommandLine 集合中注册的标志名称调用 flag.String、flag.Int 或类似函数。

Official Documentation

https://pkg.go.dev/flag#Var

Workarounds

  1. 95% success Ensure each flag name is unique across the entire program: use descriptive prefixes like `-server-port` and `-client-port` instead of just `-port`.
    Ensure each flag name is unique across the entire program: use descriptive prefixes like `-server-port` and `-client-port` instead of just `-port`.
  2. 90% success Use separate flag sets for different packages and parse each set independently: `fs := flag.NewFlagSet("myapp", flag.ExitOnError); fs.String("verbose", "", "desc")`
    Use separate flag sets for different packages and parse each set independently: `fs := flag.NewFlagSet("myapp", flag.ExitOnError); fs.String("verbose", "", "desc")`

中文步骤

  1. Ensure each flag name is unique across the entire program: use descriptive prefixes like `-server-port` and `-client-port` instead of just `-port`.
  2. Use separate flag sets for different packages and parse each set independently: `fs := flag.NewFlagSet("myapp", flag.ExitOnError); fs.String("verbose", "", "desc")`

Dead Ends

Common approaches that don't work:

  1. 70% fail

    The default set is still used; panics persist unless all flags are on a custom set.

  2. 80% fail

    The flag name string is what matters; variable name change doesn't affect registration.